On 29/11/2026 20:08, Bonita Montero wrote:
> Am 29.11.2026 um 17:19 schrieb Scott Lurndal:
>
>> Commercial operating systems have used "virtual functions" in C pretty
>> extensively over the last forty years (consider the Unix VFS layer
>> or generic device driver interfaces for example).
>
> Virtual functions in C++ need less storage since you need only one
> virtual method table pointer per baseclass. C-code is typically with
> one fuction pointer as a struct member. And C++ virtual functions are
> easier to handle since they're automatically set by the constructor.
>
>
True.
But they are also more indirect than function pointers contained directly in a struct (the common C method). This can sometimes be significant, so there are pros and cons to both solutions. The virtual method table is usually the better tradeoff, which is why it is used by C++, but it is not always so.
And of course you can do the same in C, albeit with more manual coding.
// C++
struct Foo {
int x;
int y;
virtual void do_this();
virtual int do_that(int z);
};
Foo foo;
foo.do_this();
// C with "traditional" C virtual functions:
struct Foo {
int x;
int y;
void (*do_this)(void);
int (*do_that)(int z);
};
struct Foo foo;
foo.do_this();
// C with virtual method table :
struct Foo_methods {
void (*do_this)(void);
int (*do_that)(int z);
};
struct Foo {
struct Foo_methods * p_vmt;
int x;
int y;
};
struct Foo foo;
foo.p_vmt->do_this();