#include <iostream>
class SuperBase
{
public:
int Sb;
};
class Base1:virtual public SuperBase
{
public:
int a;
};
class Base2:virtual public SuperBase
{
public:
int b;
};
class Derived: public Base1,public Base2
{
public:
int c;
};
int main()
{
using namespace std;
cout<<sizeof(Derived);
return 0;
}
output is showing 24
but it should show 20 because
int sb 4 bytes
int a 4 bytes
int b 4 bytes
int c 4 bytes
vbptr 4 bytes
total 20 bytes
as we are using virtual inheritance concept so int sb should not be calculated twice isn’t?
24 is probably:
On my (32bit) compiler,
sizeof(Derived)is 24 andsizeof(Base1)is 12, though, suggesting that the overhead isn’t always 8.I would guess that the 8 consists of one vtable (or similar) pointer at the start of the Base1 subobject, and another one in the Base2 subobject, which will be used when a pointer to the object is cast to
Base2*. The issue with multiple inheritance is that the offset of Base1 from the start of the object can’t be the same as the offset of Base2 from the start of the object.In particular, this means that for one of Base1 and Base2, the offset when its a base class subobject of Derived is different from when BaseN is the most derived class. But when you cast to Base2*, the resulting value must point to something that “looks like” a Base2. Hence there’s some extra overhead in cases where virtual inheritance actually results in a shared base class.
Another way to do it would just be to make
sizeof(SuperBase)4,sizeof(Base1)andsizoef(Base2)both 12 (two ints and a vtable pointer), andsizeof(Derived)equal to 28: 4 for Sb, 4 each for a,b,c, and 4 each for three vtable pointers, one each in Base1, Base2 and Derived. But your compiler has (I think) done you a favour, and arranged for Derived’s vtable pointer to be in the same place as that for Base1, as is normal with single inheritance.In all cases when I say “vtable pointer”, it may or may not be the exact same thing that’s used for virtual functions, but it’s some kind of class meta-data. Perhaps it’s just a pointer or offset used to reach a base class.
I drew some little diagrams here that might help:
Why can't you use offsetof on non-POD structures in C++?