I am reading -- 3.4 Inheritance and the Data Member. It says "the language guarantee of the integrity of the base class subobject within the derived class." Also it gives an example as follows:
class Concrete1
{
private:
int val;
char bit1;
};
class Concrete2 : public Concrete1
{
private:
char bit2;
};
class Concrete3 : public Concrete2
{
private:
char bit3;
};
The Concrete1 object model is:
4 bytes for val,
1 byte for bit1,
3 bytes padding.
// 8 bytes in total.
The Concrete2 object model is:
8 bytes for Concrete1 subobject,
1 byte for bit2,
3 bytes padding.
// 12 bytes in total.
Similarly, the Concrete3 object model is 16 bytes.
Concrete2 object member bit2 doesn't use the padding part of Concrete1 subobject, that's why it is 12 bytes. But when I tried the example in gcc 4.4.7, Concrete2 object and Concrete3 object are the same size as Concrete1 object -- 8 bytes. So I'm guessing gcc uses the padding part of Concrete1 object to store bit2 and bit3. I'm calling them "not-use-padding" way and "use-padding" way for short.
In order to explain why the padding part is not used, the book gives the following code:
Concrete2 *pc2;
Concrete1 *pc1_1, *pc2_2;
pc1_1 = pc2;
*pc1_1 = *pc2_2; // pc1_1 may point to a Concrete2 or Concrete3 object.
In "not-use-padding" way, the Concrete1 object pointed to by pc2_2 will be copied to the Concrete1 subobject of the Concrete2/Concrete3 object pointed to by pc1_1. The book also says it's a "memberwise" copy, but it looks more like an "object" copy because it implies the padding part is also copied.
In "use-padding" way, the book says it will override the bit2 member because the corresponding byte of *pc2_2 is a padding byte. Again, I tried it with gcc 4.4.7, it turned out the bit2 member is not overridden. So I'm guessing the copy is a real "memberwise" copy, just val and bit1 are copied.
So my questions are: 1. Am I correct about the gcc activities: "use-padding" way and real "memberwise" copy? 2. The private members of a base class can't be accessed in derived class, but derived class object contains all the private members in its base class subobject (val and bit1) in object model. Why it is designed to contain base class private members even if they can not even be accessed in derived class object? Just for copy operations like *pc1_1 = *pc2_2; ?
Thanks