c++ - why size of extreme down Derived class (multiple virtual inheritance) includes two times of size of member of superclass? -


#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 showing 24 should show 20 because int sb 4 bytes int 4 bytes int b 4 bytes int c 4 bytes vbptr 4 bytes total 20 bytes 

as using virtual inheritance concept int sb should not calculated twice isn't?

24 probably:

  • 4 sb
  • 4 a
  • 4 b
  • 4 c
  • 8 overhead of virtual inheritance.

on (32bit) compiler, sizeof(derived) 24 , sizeof(base1) 12, though, suggesting overhead isn't always 8.

i guess 8 consists of 1 vtable (or similar) pointer @ start of base1 subobject, , 1 in base2 subobject, used when pointer object cast base2*. issue multiple inheritance offset of base1 start of object can't same offset of base2 start of object.

in particular, means 1 of base1 , base2, offset when base class subobject of derived different when basen derived class. when cast base2*, resulting value must point "looks like" base2. hence there's overhead in cases virtual inheritance results in shared base class.

another way make sizeof(superbase) 4, sizeof(base1) , sizoef(base2) both 12 (two ints , vtable pointer), , sizeof(derived) equal 28: 4 sb, 4 each a,b,c, , 4 each 3 vtable pointers, 1 each in base1, base2 , derived. compiler has (i think) done favour, , arranged derived's vtable pointer in same place base1, normal single inheritance.

in cases when "vtable pointer", may or may not exact same thing that's used virtual functions, it's kind of class meta-data. perhaps it's pointer or offset used reach base class.

i drew little diagrams here might help:

why can't use offsetof on non-pod structures in c++?


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -