srinuvenu srinuvenu - 1 year ago 36
C++ Question

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

I have the following code:

class A {
int i;

class B : public A {
int j;

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download