Chapter II Data Member Model
1.1. Inheritance and Data Member
Example of the following example:
0001 class Concrete10002 {0003 public: 0004 int val; 0005 char bit1; 0006}; 0007 class Concrete2: public Concrete10008 {0009 public: 0010 char bit2; 0011}; 0012 class Concrete3: public Concrete20013 {0014 public: 0015 char bit3; 0016 }
The inheritance relationship is as follows:
Concrete1
Concrete2
Concrete3
Correct object memory layout
Concrete1 Object Concrete2 Object Concrete3 Object
4
Int Val
1
Char bit1
3
Padding 3 bytes
8
Concrete1
1
Char bit2
3
Padding 3 bytes
12
Concrete2
1
Char bit3
3
Padding 3 bytes
Verify
0001 #include
The output is:
8
12
16
As can be seen from the above model structure, the subclasses inherit the data of the parent class, and inherit the "extra" byte introduced by the parent class due to the principle of complement. Why don't you remove the "extra" bytes introduced by the child class while inheriting the parent class. Why don't you convert a model into a form in order to save memory, reduce the waste of object memory space caused by inheritance relationships?
Concrete1 Object Concrete2 Object Concrete3 Object
4
Int Val
1
Char bit1
3
Padding 3 bytes
4
Int Val
1
Char bit1
1
Char bit2
2
Padding 2 bytes
4
Int Val
1
Char bit1
1
Char bit2
1
Char bit3
1
Padding 1 Bytes, the memory occupancy size of the three objects becomes 8 bytes, so it will save memory when creating multiple derived class objects.
This model does not use this model because the model will generate unpredictable errors when copying the object, for example:
0001 Concrete2 * PC2; 0002 Concrete1 * PC1; 0003 PC2 = New Concrete2; 0004 PC1 = New Concrete1; 0005 * PC2 = * PC1;
The above model model will generate unpredictable errors in the fifth line because the data member of the Concrete2 object is destroyed when copying the Concrete1 object.
Bit2 will be assigned an uncertain value, breaking the original data content, this behavior is not expected.
Concrete1 Object Concrete2 Object
4
Int Val
1
Char bit1
3
Padding 3 bytes
4
Int Val
1
Char bit1
1
Char bit2
2
Padding 2 bytes
Copy
Similarly, Concrete1 ---> Concrete2, Concrete2 -à Concrete3 also destroyed data members.