Skip to content

Instantly share code, notes, and snippets.

@Wollw
Created April 3, 2012 02:59
Show Gist options
  • Save Wollw/2288964 to your computer and use it in GitHub Desktop.
Save Wollw/2288964 to your computer and use it in GitHub Desktop.
Object Encapsulation in ANSI C
#include <malloc.h>
#include "class.h"
/* This is the actual implementation of the class.
* Because this file isn't included by main.c
* code in main.c can not access foo except through
* the functions declared in class.h.
*/
struct my_class_s {
int foo;
};
void set_foo(my_class *this, int n) {
this->foo = n;
}
int get_foo(my_class *this) {
return this->foo;
}
my_class * new_object() {
return malloc(sizeof(my_class));
}
void free_object(my_class *this) {
free(this);
}
/* This is a very simple example class with encapsulation
* in ANSI C. It provides encapsulation by only declaring the
* struct for the class in this header file and defining the "class"
* only in the source file itself. This means that source files that
* include this file don't know about the actual contents of the struct
* and therefore can not access any members of an object.
*
* I wrote this after reading C++ FQA Lite 7.5[1] which hinted at this.
*
* [1] http://yosefk.com/c++fqa/class.html#fqa-7.5
*/
#ifndef MY_CLASS_H
#define MY_CLASS_H
/* Our declaration of the class my_class */
struct my_class_s;
typedef struct my_class_s my_class;
/* This constructor returns a pointer to a new object of the class
* my_class or it returns NULL if it fails. free_object destroys it.
*/
my_class *new_object();
void free_object(my_class *this);
/* These methods are used for setting and getting the value of the
* foo member of my_class objects.
*/
void set_foo(my_class *this, int n);
int get_foo(my_class *this);
#endif
/* This is a simple example of using encapsulation in ANSI C.
* Check the comments in class.h for more details.
*/
#include <stdio.h>
#include "class.h"
int main() {
my_class *obj = new_object();
assert(obj != NULL);
set_foo(obj, 123);
printf("%d\n", get_foo(obj));
free_object(obj);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment