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)
?
The derived class doesn't "inherit" the private members of the base class in any way - it can't access them, so it doesn't "inherit" them.
Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.
Size of a derived class Of course, a derived class has all data members of the base class it inherits and does it has its own copied of those data members too. Thus size should be the size of base class data members + size of derived class data members.
all member variables are inherited. the private protected public
modifiers only alter who has access to those variables
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With