Is there any space or performance overhead incurred in using virtual inheritance? Regardless of how small the overheads might be, I'm curious to learn about them.
If you're up to giving a detailed answer (and thank you in advance if you do), then feel to mention how any specific how compilers might do virtual inheritance, especially GCC and MSVC. I'm coming from the C world, so I don't mind hearing the guts of things; the guts are in fact what I'm looking for.
#include <cstdio>
usingnamespace std;
class Base
{
int x;
};
class DerivedVirtual : publicvirtual Base
{
int y;
};
class DerivedPlain : public Base
{
int y;
};
int
main(void)
{
DerivedVirtual dv;
DerivedPlain dp;
printf("sizeof(int): %d\n", (int)sizeof(int));
printf("%d\n", (int)sizeof(dv));
printf("%d\n", (int)sizeof(dp));
}
It's clearly the word "virtual" making the difference. No?
In this case, yes. The extra bytes is for a vtable pointer which the compiler is adding to the class due to virtual inheritance. Usually the point of inheritance is to override behavior so you need virtual methods and thus a vtable pointer already. The example you gave may be a bit contrived, hence my original comment.
According to effective c++ third edition--item 40
virtual inheritance always has to pay some price, both on speed and space
The details may change between different compilers
But you have to pay for virtual inheritance
Don't use it if you don't need it
Virtual inheritance always be used when you need multiple inheritance
Maybe you should study what is the idea of multiple inheritance before you delve into virtual inheritance
Well, since c++ is a multi-paradigm language, we don't need to force ourselve to use virtual inheritance
or feel compelled to design the program by the way of oop
please feel free to correct me if there are any errors, thanks