When C ++ allows access to protected members, it only applies to members of this object (as mentioned here and here ). The code x = p_arr[i]->function() tries to call the method on another object, so the compiler complains.
To fix your code, you can make the function public or add a friend declaration in baseClass , for example:
class baseClass { public: virtual int function() = 0; };
or
class baseClass { protected: friend class derived_C; virtual int function() = 0; };
However, to preserve access to protected and not specify the name of the derived class in the base class, you can fix your code by adding the static access function to the base class:
class baseClass { protected: virtual int function() = 0; static int call_the_function_on_object(baseClass& obj) {return obj.function();} };
Use it (in a derived class) as follows:
x = call_the_function_on_object(*p_arr[i]);
You can also give the accessor function the same name, but then if your derived_C overrides the virtual method, it will hide the access function. You can fix this by accessing the base class explicitly:
class baseClass { protected: virtual int function() = 0; static int function(baseClass& obj) {return obj.function();} }; ... class derived_C:public derived_A, public derived_B { ... x = baseClass::function(*p_arr[i]); ... }
source share