4 ms·
I skimmed the first couple of chapters and the syntax you have to go through to make this work looks painful at best. void * everywhere. Structs with C's functi
by WoodenChair 3y ago
I skimmed the first couple of chapters and the syntax you have to go through to make this work looks painful at best. void * everywhere. Structs with C's function pointer syntax all over the place... It looks like it can certainly work, but it's not going to be pleasant compared to almost anything designed for OO.
- rectang 3y agoYou’re right about the syntax becoming extremely tedious. Eventually you wind up doing waaaay too many function pointer casts and typedefs. The appeal of this approach, to me, is mostly pedagogic rather than practical: stuff designed for OOP isn’t generally going to let you control struct layout to the degree that C will, making it harder to get your hands dirty and learn core concepts.
- G3rn0ti 3y agoYou don’t need all that to emulate objects in C. Instead use this recipe: - classes <-> compilation units - objects <-> structs - methods <-> functions receiving a pointer to a struct as first argument; use name of the class as prefix e.g. Point3D_scale(Point3D *self, double factor) - constructors are just methods and initialize the struct - destructors are just methods and free all memory occupied by the struct Inheritance is a bit more difficult this way but as others pointed out already it is way over used IMHO. But if you really want to do that you could design a child class by using a struct pointing to the parent struct and using that to manually delegate all inherited method calls to the parent. You could probably write a fancy macro automating this delegation for you.
- ChrisMarshallNY 3y agoI did “false object” programming with C, back in the mid-90s. I never read this book, but we came up with similar approaches. I got the idea from QuickDraw GX. I passed around structs, as “nouns,” and some had built-in “verbs.” I used function pointers, and these created kind of a “poor man’s vtable.” Not exactly “polymorphism,” but similar. I needed to do it for a modular imaging peripheral SDK. Back then, the only reliable way to cross an external module boundary was with ANSI C (stack conventions). It worked quite well, as they were still using the same SDK, 25 years later. WFM. YMMV.
- gpderetta 3y ago> I used function pointers, and these created kind of a “poor man’s vtable.” Not exactly “polymorphism,” but similar. It is indeed polymorphism. A form of interface polymorphism I guess.
- ChrisMarshallNY 3y agoWell, the hierarchy needed to be manually maintained. There wasn't really any kind of "super" or "parent."