I always thought that I understood inheritance, but obviously I don't. I would like to call a protected member function of another instance of the same parent class from a child class like in the following example code:
#include <iostream>
class Parent {
protected:
void doStuff(){
std::cout << 5 << std::endl;
}
};
class Child : public Parent {
public:
void pubfunc(Parent* p){
p->doStuff();
}
};
int main(){
Child* c = new Child();
Parent* p = new Parent();
c->pubfunc(p);
return 0;
}
However, compilation of this code fails with:
In member function ‘void Child::pubfunc(Parent*)’:
error: ‘void Parent::doStuff()’ is protected
error: within this context
I wouldn't want to make the Child
class a friend
of the Parent
class to avoid forward declarations and forward includes of child classes as much as possible. Also, I don't want to make doStuff
public, because it can really mess up the internal structure of Parent
when used in the wrong circumstances.
Why does this error happen, and what is the most elegant way to solve it?