Inheritance can be implemented as well:
typedef struct AdvancedFoo {
BaseFoo super;
int a, b, c;
thinkfunc_t thinkHarder;
} AdvancedFoo;
Since `super` is the first member in the struct, a pointer to an AdvancedFoo can be used as a pointer to BaseFoo as well: AdvancedFoo *advFoo = AdvancedFoo_new();
advFoo->thinkHarder(advFoo, advFoo->a);
((BaseFoo*) advFoo)->doThink(advFoo, some_int_method());
Of course, this inheritance pattern can continue in multiple steps.I don't see the need to do the "ret->doThink = null_think;" since you always pass ret to the function. Just call null_think( ret... )
Ah, but what if the object is handed over to some other deep end of the code? We want to bake the null behavior into it so that any Foo knows how to think itself--calling code just needs to be aware that any Foo object will always have a valid think callback defined.
This is basically the null-object pattern.
So, let's say I have a structure which I will use to represent objects in my game:
So, if I want to create a new BaseFoo, I just call Foo_new() and I'm off to the races; I get back a Foo object that, during my update loop, I can fiddle with: So, that's kind of cool, but what if I want to create a new, better foo, that actually moves? I do this: So, this is very bland, but it gets across the idea that function pointers let me easily override member methods on class instances. You can imagine that, with a little cleverness, you can store arbitrary data into the struct, along with a table of function pointers to instance methods (a virtual function table).This is a very fun, very deep rabbit hole.
In a lot of ways, you basically fake the type of prototypical inheritance you'd expect from, say, JavaScript.
EDIT:
Elaborating on another point--it's very common to use function pointers in a struct that then gets filled out by a dll or shared library.
For example, let's say that I've got a renderer that draws 3D stuff and conforms to an API. At runtime, I check what driver the user wants to use (software renderer, Direct3D, or OpenGL), and then I fill out the function pointers of that structure to point at the architecture and driver-specific methods I'd like to use.
The rest of my code doesn't change, because it only ever calls the interface exposed by the structure--the actual addresses pointed to by the function pointers are irrelevant.