C ++ inheritance (six) --- diamond inheritance in object size class

Diamond inheritance in object size class

Size is empty class 1
class A
{

};

int main()
{
	cout << sizeof(A) << endl;
}

Here Insert Picture Description

Inherit the size of the classes in the case of not processing

Here Insert Picture Description

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;
}

Here Insert Picture Description

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:
Here Insert Picture Description
Therefore, the size of the class-D is 20 bytes.

Class size in the case of D calculated virtual inheritance

Here Insert Picture Description

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
}

Here Insert Picture Description
In a (d), we learned , virtual inheritance class object model as follows:
Here Insert Picture Description
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:
Here Insert Picture Description
Therefore, B is derived size is 16 bytes. Similarly derived C.

D-size object model

Here Insert Picture Description
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.

Published 52 original articles · won praise 26 · views 3412

Guess you like

Origin blog.csdn.net/weixin_43796685/article/details/103599466