I’m currently using OOP techniques in C, and I’ve used the known idiom of a child class having a parent class instance inside its struct, like this:
struct parent{
void (*doSomething)(struct parent *parent);
};
struct child{
struct parent base;
int (*doSomethingCooler)(struct child *child);
};
Now, my methods are prefixed with the class they belong to:
void parent_doSomething(struct parent *parent);
int child_doSomethingCooler(struct child *child);
With overloading, I have
void child_doSomethingCool(struct parent *parent);
that I set to parent->doSomething on the child constructor function.
Anyway, the problem arises when I have a child instance, and I want to call parent methods. Immediately, I have to cast (sort of dynamic_cast in C) my instance pointer to the parent class type, and this fastly pollutes my code.
The second idea was to define all methods to receive void * “this” parameters, and internally cast them to the right class. This simplifies the usage from client code, but expose the code to nasty bugs, like passing invalid references, or references of the wrong type.
What are the pros and cons of each implementation?
With the new type generic feature of C11 you could uniformly access the parent part:
and then you could overload your function name with a macro
as you can see from these examples this wouldn’t work too well with OO notation of calling a “method” through the pointer such as
p->doSomething(), but this could be a start.