Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 428
srinuvenu Avatar asked Jul 04 '11 07:07

srinuvenu


People also ask

Does derived class inherit private members?

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.

Can derived classes access private members of base class?

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.

Why is the base class called when a derived class is created?

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.

How do you determine the size of a derived class?

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.


2 Answers

all member variables are inherited. the private protected public modifiers only alter who has access to those variables

like image 138
Karoly Horvath Avatar answered Nov 30 '22 19:11

Karoly Horvath


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.

like image 27
In silico Avatar answered Nov 30 '22 19:11

In silico