24 is probably:
- 4 for Sb
- 4 for a
- 4 for b
- 4 for c
- 8 for the overhead of virtual inheritance.
On my (32bit) compiler, sizeof(Derived)
is 24 and sizeof(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)
and sizoef(Base2)
both 12 (two ints and a vtable pointer), and sizeof(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++?