why size of extreme down Derived class (multiple virual inhertance) includes two times of size of member of superclass?

#include <iostream>
class SuperBase
    int Sb;
class Base1:virtual public SuperBase
    int a;
class Base2:virtual public SuperBase
    int b;
class Derived: public Base1,public Base2
    int c;

int main()
    using namespace std;
    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 r using virtual inheritance concept so int sb should not be calculated twice isn't?


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 strucutures in C++?

Need Your Help

Lib.Web.Mvc with edittype select and multiple true

c# jqgrid lib.web.mvc

After read this post of a custom implementation of DataEvents on Lib.Web.Mvc.

Setting up user specific preprocessor macros for Xcode

objective-c xcode xcode4.5

I'd like to be able to have specific code blocks such as #ifdef SOME_VARIABLE and the value of variable would be filled at project's build time if the project is being built on a specific user's ma...