You can implement polymorphism with regular functions and virtual tables (vtables). Here's a pretty neat system that I came up with (based on C ++) for programming exercises: 
Constructors allocate memory and then call the init function of the class in which the memory is initialized. Each init function must also contain a static vtable structure containing pointers to virtual functions (NULL for pure virtual). Derived functions of the init class call the function of the init superclass before doing anything else.
A very good API can be created by implementing shells of virtual functions (not to be confused with the functions that vtables points to) as follows (add a static inline in front of it if you do this in the header)
int playerGuess(Player* this) { return this->vtable->guess(this); }
Single inheritance can be accomplished by overusing the binary layout of the structure: 
Note that multiple inheritance is more messy, as you often have to adjust the pointer value when casting between hierarchy types.
Other type-specific data can also be added to virtual tables. Examples include runtime type information (for example, a type name as a string), a link to the vtable superclass, and a chain of destructors. You probably need virtual destructors where the destructor of the derived class lowers the object to its superclass, and then recursively calls the destructor of it, etc., until the destructor of the base class is reached and which finally frees the structure.
Encapsulation was accomplished by defining structures in player_protected.h and implementing functions (denoted by vtable) in player_protected.c and similarly for derived classes, but this is rather clumsy and this degrades performance (since virtual wrappers cannot be placed in headers), therefore I would recommend against this.
Tronic Feb 02 2018-10-02T00 : 00Z
source share