Diamond inheritance in object size class
Size is empty class 1
class A
{
};
int main()
{
cout << sizeof(A) << endl;
}
Inherit the size of the classes in the case of not processing
class A
{
protected:
int _a;
};
class B : public A
{
protected:
int _b;
};
class C : public A
{
protected:
int _C;
};
class D : public B, public C
{
protected:
int _d;
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
cout << sizeof(D) << endl;
}
Class D object size calculated
As shown above, the members of the two D inherits class A, and is not superimposed, so B there are five members of type int:
Therefore, the size of the class-D is 20 bytes.
Class size in the case of D calculated virtual inheritance
class A //基类
{
protected:
int _a1 = 1;
int _a2 = 10;
};
class B : virtual public A //B继承A
{
protected:
int _b = 2;
};
class C : virtual public A //C继承A
{
protected:
int _c = 3;
};
class D : public B, public C //D继承B、C
{
protected:
int _d = 4;
};
int main()
{
cout << sizeof(A) << endl; //8
cout << sizeof(B) << endl; //16
cout << sizeof(C) << endl; //16
cout << sizeof(D) << endl; //28
}
In a (d), we learned , virtual inheritance class object model as follows:
to know, in order to prevent repeat A class variable redundancy, using _vbptr virtual base table pointer to access virtual base tables give the offset method , to access a member of class a.
Size class Object Model B
Therefore, in this embodiment virtual inheritance, class object model class B is:
Therefore, B is derived size is 16 bytes. Similarly derived C.
D-size object model
As can be seen, D object contains two pointers, the data 5, and eliminates redundant data class A succession. Therefore, the size of the class-D is 28 bytes.