I have the following code:
class A {
private:
int i;
};
class B : public A {
private:
int j;
};
When I check sizeof(B)
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
.