Re:OOP in C
by zabzonk on Sunday January 08, 2023 @06:27AM
(#34298192)
what does an "object" look like? how do i derive from it?
[ Parent
| on HN ]
Any struct. Only requirement would be that the first element can be casted to a point to a class object containing the vtable. I'ved edited to fix the casting so it actually compiles, and to use a void * in the argument list, as is what you'd actually usually do.
generic base type struct
Easy; a subclass struct embeds the superclass struct as its first member.
Simple example here: https://embeddedgurus.com/state-space/2008/01/object-based-p...
Lots more here: https://stackoverflow.com/questions/351733/how-would-one-wri...
Having spent quite some time down that rabbit hole back in the days, I'd definitely recommend against pushing C in that direction. Few people love GObject, for good reasons.
Embedding combined with the container_of-macro [0] is a much more constructive approach from my experience.
[0] https://stackoverflow.com/questions/15832301/understanding-c...