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

前端 未结 7 1729
谎友^
谎友^ 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:14

    This has already been answered in a few other answers: access specifiers restrict access, but the member attributes of the class are still inherited.

    I just wanted to provide a rationale, as I usually learn better when I see the reasons for that. Basically, when you inherit from an type, the derived type contains a subobject of the base type, as small or large as the base might be. The reason for needing all of the member variables is that the derived object is a base object, and base level member functions can be called on it. Even if the derived type cannot access the private member attribute, the base methods that can be called on that object might still need to access it, so the members must be there:

    class base {
       int x;
    public:
       base() : x(0) {}
    // ...
       void printout() {
          std::cout << x << std::endl;
       }
    };
    class derived : public base {
    // ... assume that derived does not hide `printout`
    };
    int main() {
       derived d;
       d.printout();  // this requires access to d.base::x
    }
    

    This is only a simple example, and there are a few things that you can say here to argue that in some cases x can be made unneeded (we are overriding/hiding printout in the derived object...) but the language still allows you to access a hidden/overridden member method by qualifying, so d.base::printout() would still access printout at the base level, and that in turns requires x.

提交回复
热议问题