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

前端 未结 7 1725
谎友^
谎友^ 2021-02-09 19:52

I have the following code:

class A {
  private:
    int i;
 };

class B : public A {
 private:
  int j;
 };

When I check sizeof(B)

相关标签:
7条回答
  • 2021-02-09 20:29

    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.

    0 讨论(0)
提交回复
热议问题