class Base
{
private:
int var;
};
class Child : protected Base
{
void someFunc()
{
var = 5; // Error: Base::var is private
}
};
What's wrong is there?
class Base
{
private:
int var;
};
class Child : protected Base
{
void someFunc()
{
var = 5; // Error: Base::var is private
}
};
What's wrong is there?
Try this:
class Base
{
protected:
int var;
};
See this reference for the difference between private, protected, and public in c++.
Even with protected
or private
inheritance, you do not gain access to the use of private
members in the parent classes.
Make them protected
if you really need access to them directly.
Edit: dang, beaten to it.
You have declared var
to have private access in Base
. Private means that only this class can see that variable, not subclasses.
I think you probably want protected access in this case: protected means this class and any subclass can see it.
Edit: Dang, also beaten to it.
What's wrong is that you're attempting to access a private variable from another class that's not a friend.
The easy way out is to make var
protected rather than private, but that introduces additional dependencies. Typically, variables should be private. Stroustrup, in his book "Design and Evolution of C++", regretted having introduced protected
. He considers protected data to be an invitation to problems, and in his experience it isn't necessary. Opening data members to arbitrary manipulation by any declared subclass really isn't much better than making them public.
When tempted to use protected data members, you should ask yourself what you're really trying to accomplish. This is obviously a constructed example. If there was some reason for Child
to modify var
, that reason could be expressed in a function name, and protected functions aren't nearly as bad as protected data members.