I have the following code:
class A {
private:
int i;
};
class B : public A {
private:
int j;
};
When I check sizeof(B)
You misunderstand what private
does. In your code snippet it simply prevents non-members and non-friends of A
from accessing i
. It's just an access-control modifier. Instances of B
will have data members of A
, even though B
won't have (direct) access to it.
An analogy that shows that this does in fact make sense:
class Human
{
protected:
void UseCognitivePowers() { brain.Process(); }
private:
Brain brain;
// ...
};
class StackOverflowUserInSilico : public Human
{
private:
void AnswerStackOverflowQuestion(int questionId)
{
// ...
// magic occurs here
// ...
UseCognitivePowers();
}
};
Even though brain
is private in the Human
class, StackOverflowUserInSilico
will have a Brain
since StackOverflowUserInSilico
derives from Human
. This is needed, otherwise the UseCognitivePowers()
function won't work even though StackOverflowUserInSilico
inherits the method from Human
.
Of course whether subclasses of Human
will actually take advantage of the UseCognitivePowers()
method afforded to them by the Human
class is a totally different matter.