Read the Deep Exploration C + + object model The impact of hierarchical inheritance on memory layout __c++

Source: Internet
Author: User

Please see the following code:

Class concrete
{public
:
private:
	int val;
	Char C1;
	char C2;
	char c3;
};
I run on my computer and get the size of the class concrete 8byte, and I would like to meet our expectations (Val:4byte, C1:1byte, C2:1byte, C3:1byte), one byte aligned to the other, just 8byte.

What would be the effect on space if I changed to the following way to be cool?

Class Concrete1
{public
:
private:
	int val;
	char C1;
};

Class Concrete2:public Concrete1
{public
:
private:
	char C2;
};

Class Concrete3:public Concrete2
{
private:
	char c3;
};
So what is the size of the space to be obtained?


It's twice times above. So why is that so?

Because the C + + standard stipulates:

The base class object that appears in the inheriting class has its integrity.

So let's analyze the Concrete1 object, which contains two data members: Val and C1, plus 5byte, plus byte alignment is 8byte.

Concrete2 plus Concrete1 data, plus 1byte, just 8+1=9byte, plus byte alignment is 12byte.

Concrete3 plus Concrete2 object plus 1byte, just 12+1=13byte, plus byte alignment is 16byte.

Then why do we not add the 1byte to the Concrete1 object in Concrete2 and Concrete3?

is to meet the assurance of C + +.
Let us give an example to illustrate that

If you have the following code:

	Concrete2 *p2 = new Concrete2;
	Concrete1 *p1 = p2;
assigning P2 objects to P1, in theory, is the memberwise assignment (copy) of the execution, so if our Concrete2 1byte object is bound to the Concrete1 object, it is populated with 3 bytes of Concrete1 alignment, So P1 's data also contains Concrete2 1byte, so that's wrong.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.