C does not support inheritance or OOP, so you need to implement it yourself. There are a couple of useful techniques that are helpful
struct extension
C guarantees that the first field in a struct will be at offset 0, so you can freely cast between a pointer to a struct and a pointer to the struct's first field. This allows easy extension of a struct for deriving:
struct BaseClass {
...whatever
};
struct DerivedClass {
struct BaseClass base;
... derived class additions
};
Here you can take a (pointer to) an instance of DerivedClass and cast to BaseClass *
and it will work. You can also cast a BaseClass *
back to a DerivedClass *
if the pointer is known to point at an actual DervicedClass
metaclass objects
You can implement OO dispatch using metaclass structs containing function pointers
struct BaseClass;
struct BaseMetaclass {
void (*method1)(struct BaseClass *);
int (*method2)(struct BaseClass *, int);
};
struct BaseClass {
struct BaseMetaclass *isa;
....
};
Now you can create a single instance of BaseMetaclass used by all instances of BaseClass and call the method via the isa
pointer.
base_obj->isa->method1(base_obj);
Derived classes can use BaseMetaclass directly if they don't need to add any new methods, or can define a DerivedMetaclass
using struct extension with additional fields. You can also put any other class-oriented data you like in the metadata objects (a string constant with the name of the class is useful).