4 ms·
You can still use virtual function calls in plain C, you just do things the same way that C++ does things internally. Your first member of the struct is a Vtab
by Dwedit 3y ago
You can still use virtual function calls in plain C, you just do things the same way that C++ does things internally. Your first member of the struct is a Vtable, and you need to assign that member when you create the object. Your first parameter for the virtual method calls is a "this" pointer.
- binary132 3y agoSlight detail: there only needs to be one instance of the vtable per class, and objects of that type only need to contain a pointer to it.
- Dwedit 3y agoAnd you can also make the vtable `const` so it goes into the read-only data section.
- huhtenberg 3y agoBy the same argument we don't really need C to begin with, because things can still be coded in assembly. It all boils down to convenience of reducing boilerplate. As the meme goes - "You don't need sneakers to run, but they sure help."
- phkahler 3y agoAnd if I understand your point its that we should embrace higher level tools rather than trying to build abstractions in lower level tools. In that case OP should just use C++ rather than trying to build an abstraction into C. That going higher level is actually why C++ was created in the first place.
- huhtenberg 3y agoThe point was that if there's a certain coding pattern that can be accommodated by adding a new language feature, it is worth considering. The fact that it's readily doable with some effort in some other way is not an argument against it. C++ started as a reasonable extension to C, but now it's just something else (nor does it even want to be seen related to C now anyway). Extending C with something new, without rushing, is a perfectly fine idea.
- o11c 3y agoThe problem with rolling your own virtual tables without compiler support is that devirtualization is generally not possible, even in fairly easy cases.
- Dwedit 3y agoIf by "devirtualization" you mean inlining the virtual method and associated optimizations, that can be done with If-else (checking which vtable it is), then explicitly calling the function. Failure to find a known method can proceed to calling the function pointer.
- o11c 3y agoSpeculative or unconditional devirtualization are reasonable things to do if you are the compiler. Writing code by hand, it's quite unwieldy, since the compiler doesn't know that a `FinalFooFrobber` always contains has its vtable set to `FrobberVtable foo_vtable`, which often appears only after inlining. Asking C programmers to do inlining by hand is not sane. This isn't like interpreted languages where inlining sucks - here, the compiler is quite capable of it, just the vtable stuff confuses it.
- brcmthrowaway 3y agoIsn't this GObject?