Multiple protected inheritance with polymorphism

My question is about multiple inheritance of protected function and polymorphism. it is rather difficult to describe, so I hope it will be clear enough.

says I have three classes:

class baseClass { protected: virtual int function() = 0; }; class derived_A:public baseClass { int function() { //implementation 1 }; } class derived_B:public baseClass { int function() { //implementation 2 }; } class derived_C:public derived_A, public derived_B { baseClass ** p_arr; //array of pointers of baseClass kind (polymorphism) int x=0; for (int i=0; i<arraySize; i++) // array size = many classes like derived_A, derived_B... { x = p_arr[i]->function(); //I already have function that builds this array //it is not the question so I didn't put it here. // process x } 

Finally, my question is: how can I access this "protected function ()" from a derived class (inside a for loop)? I'm a little confused ... and will be happy for the explanation.

thanks.

}

+6
source share
2 answers

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]); ... } 
+2
source

In this case, your function() is private in derived classes. So, from derived_C you cannot directly access this function.

However, if you are ready to do this public/protected . Then you can use: -

 derived_C dc; dc.derived_A::function(); dc.derived_B::function(); 
+1
source

Source: https://habr.com/ru/post/980496/


All Articles