4 ms·
TLDR: Put data members in a struct. Write a function per "method" and pass in the `this` pointer. Simple and effective. BUT: inheritance. C++ has subclasses (`
by ryanianian 4y ago
TLDR: Put data members in a struct. Write a function per "method" and pass in the `this` pointer. Simple and effective.
BUT: inheritance. C++ has subclasses (`class Manager : Employee`) and virtuals / vtable lookup on pointer access (`employee->name()` which calls `Manager::name` or `Employee::name` based on type).
What is the typical equivalent in C? Hand-rolled vtables? Or is there a general paradigm that helps to avoid the need for it in C?
I ask as a seasoned C++ and Java developer looking to improve some C code which uses this pattern in the extreme and needs some refactoring. My intuition is composition rather than inheritance, although isA is more intuitive than hasA for this code-base.
- JonChesterfield 4y agoYou're going to think this is a joke but I'm mostly sincere The right refactor is to untangle the data structures, write a lua interface to them, then port the application logic to lua. Since (one of the) lua is written in C your codebase is still all C.
- deleted 4y ago[deleted]
- kevin_thibedeau 4y agoHand rolled vtables in a struct that has metadata for the class. SQLite has a nice system where the class definition struct carries the size of the base class and any additional members so that objects can be allocated from common code and passed to their constructor method.