object oriented c
C doesn't give you much in the way of object-oriented design, but you can get pretty close when you need it.
The simplest thing is to just pass pointers to your objects into their methods:
typedef struct obj { int property; } Obj; void obj_incrementProp(Obj* self) { self->property++; }
The next best thing is to use a function pointer to bind the method to the object:
typedef struct obj { int property; void (*incrementProp)(struct obj* self) } Obj; Obj* createObj() { obj* self = malloc(sizeof(obj)); self->incrementProp = obj_incrementProp; return self; } void obj_incrementProp(Obj* self) { self->property++; }
This doesn't actually afford you much -- because there's no namespacing in C, there's nothing to stop you from just calling obj_incrementProp()
directly. You can provide some access modification by use of the static
keyword, however:
typedef struct obj { int property; void (*incrementProp)(struct obj* self) } Obj; Obj* createObj() { obj* self = malloc(sizeof(obj)); self->incrementProp = obj_incrementProp; return self; } static void obj_incrementProp(Obj* self) { self->property++; }
This means that obj_incrementProp()
cannot be called unless an Obj
instance exists, by calling obj->incrementProp(obj)
. Now, nothing stops you from passing another Obj
instance into the method, or even another type or some garbage data -- that's where we come up on the limitations of C. But, you at least can bind the method to the object and keep the method from being called any old time out of thin air.