How can I simulate OO-style polymorphism in C?

The first C++ compiler (“C with classes”) would actually generate C code, so that’s definitely doable.

Basically, your base class is a struct; derived structs must include the base struct at the first position, so that a pointer to the “derived” struct will also be a valid pointer to the base struct.

typedef struct {
   data member_x;
} base;

typedef struct {
   struct base;
   data member_y;
} derived;

void function_on_base(struct base * a); // here I can pass both pointers to derived and to base

void function_on_derived(struct derived * b); // here I must pass a pointer to the derived class

The functions can be part of the structure as function pointers, so that a syntax like p->call(p) becomes possible, but you still have to explicitly pass a pointer to the struct to the function itself.

Leave a Comment