Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



Hand 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.


You'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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: