'Calling a protected function from instance inside a derived class
Currently, I am trying to solve the following situation.
I have a classB which contains some objects from a classA. Each classA has a function foo which needs to be executed. In the context of the program it makes since that classBinherits from classA since will need all of its functionality.
I would like to call the protected function from an instance of a base class.
I have the following test code:
#include <iostream>
class baseA
{
protected:
virtual bool foo()
{
std::cout <<"Base foo in action" << std::endl;
return true;
}
};
class classB
:public baseA
{
public:
baseA obj1_;
virtual bool foo()
{
std::cout <<"I am going to call base foo" << std::endl;
bool a = obj1_.foo(); // Can't be called
}
};
int main(int argc, char** argv)
{
classB obj;
obj.foo();
return 0;
}
Currently is does not work because the function foois protected in the current context.
I get the following error: error: ‘virtual bool baseA::foo()’ is protected within this contex
Is there a way to make it work while maintaining the protected specifier?
Best regards
Solution 1:[1]
Yes, there is a way. You can put a protected "forwarding" function into the base.
struct Base {
protected:
virtual void theFunc() = 0;
static void callTheFuncOn(Base *b) {
b->theFunc();
}
};
struct Derived: Base {
void test(Base *b) {
callTheFuncOn(b);
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonathan S. |
