I have the following code:
class A {
private:
int i;
};
class B : public A {
private:
int j;
};
When I check sizeof(B)
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.