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() {
开发者_Go百科 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.
When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example, setSize
becomes private in Child
, so you can't call it from main
.
Also, size
is already private in Parent
. Once declared private, a member always remains private to the base class regardless of the type of inheritance.
You cannot access private data-members of other classes. If you want to access private attributes of a superclas, you should do so via public or a protected accessors. As for the rest, see @casablanca's answer.
#include <iostream>
using namespace std;
class Parent {
private:
int size;
public:
void setSize(int s);
int fun() //member function from base class to access the protected variable
{
return size;
}
};
void Parent::setSize(int s) {
size = s;
}
class Child : private Parent {
private:
int c;
public:
void print();
using Parent::setSize; //new code line
using Parent::fun; //new code line
};
void Child::print() {
cout << fun() << endl;
}
int main() {
Child child;
child.setSize(4);
child.print();
return 0;
}
精彩评论