One solution would be to declare a static protected function in Base that redirects the call to the private / protected function ( foo in the example).
Let's say:
class Base { protected: static void call_foo(Base* base) { base->foo(); } private: virtual void foo() = 0; }; class Derived : public Base { private: Base* b; protected: virtual void foo(){}; virtual void foo2() {
Thus, we do not break encapsulation, because the Base constructor can make an explicit choice to allow all derived classes to call foo on top of each other, while avoiding putting foo in the public interface or explicitly turning all possible Base subclasses into friends.
Furthermore, this method works whether foo virtual or not, or whether it is confidential or secure.
Here is a link to the current version of the code above and here is another version of the same idea with a bit more business logic.
Clemens sielaff
source share