srinuvenu srinuvenu - 1 month ago 6
C++ Question

Why does the size of a derived class include private members from the base class?

I have the following code:

class A {
private:
int i;
};

class B : public A {
private:
int j;
};


When I check
sizeof(B)
, it appears to be
sizeof(base) + sizeof(derived)
. However, my understanding of inheritance is that the
private
members of a base class are not inherited. Why then are they included in the result of
sizeof(B)
?

Answer Source

You either misunderstand sizeof or your misunderstand the layout (in memory) of C++ objects.

For performance reason (to avoid the cost of indirection), compilers will often implement Derivation using Composition:

// A
+---+
| i |
+---+

// B
+---+---+
| A | j |
+---+---+

Note that if private, B cannot peek in A even though it contains it.

The sizeof operator will then return the size of B, including the necessary padding (for alignment correction) if any.

If you want to learn more, I heartily recommend Inside the C++ Object Model by Stanley A. Lippman. While compiler dependent, many compilers do in fact use the same basic principles.