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)?
You either misunderstand
sizeofor 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:
Note that if
private,Bcannot peek inAeven though it contains it.The
sizeofoperator will then return the size ofB, 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.