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;
}
Change Parent to:
protected: int size;
If you want to access the size
member from a derived class, but not from outside the class, then you want protected
.
Change Child to:
class Child: public Parent
When you say class Child: private Parent
, you are saying it should be a secret that Child is a Parent. Your main
code makes it clear that you want Child to be manipulated as a Parent, so it should be public inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With