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.