I’m trying to get the following code to work, but I can’t find good-enough documentation on how C++ handles public vs. private inheritance to allow me to do what I want. If someone could explain why I can’t access Parent::setSize(int) or Parent::size using private inheritance or Parent::size using public inheritance. To solve this, to I need a getSize() and setSize() method in Parent?
class Parent {
private:
int size;
public:
void setSize(int s);
};
void Parent::setSize(int s) {
size = s;
}
class Child : private Parent {
private:
int c;
public:
void print();
};
void Child::print() {
cout << size << endl;
}
int main() {
Child child;
child.setSize(4);
child.print();
return 0;
}
When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example,
setSizebecomes private inChild, so you can’t call it frommain.Also,
sizeis already private inParent. Once declared private, a member always remains private to the base class regardless of the type of inheritance.