Search code examples
c++inheritancepolymorphismfrienddelegation

C++ allow derived classes of friend to have access to private nested class


Here's what I'm trying to do:

class A
{
    friend class C (and all of C's derived classes)
public:
    void DoAThing() { mpMyC->DelegateResponsibility(myB); }   

private:
   class B
   {
   };
   B mMyB;
   C* mpMyC;  
};

class C
{
    // No problem here- C can see B
    virtual void DelegateResponsibility(const A::B& necessaryInfo);
};

class D: public C
{
    // Uh-oh- we don't inherit friendship   
    virtual void DelegateResonsibility(const A::B& necessaryInfo);
};

In short, I have a private nested class inside A because it's an implementation detail of A. However, I'd like to delegate some responsibilities of A to C and C's derived classes to get some polymorphic behavior. I'd like to avoid having to add a friend class line every time someone derives from C. The standard workaround given for derived friend classes is "just add a protected accessor function to your base class and override it for derived members" but that only helps access private members of class A, not privately scoped classes. Is there any way to workaround this issue?


Solution

  • This should work:

    class C
    {
        typedef A::B MyB;
        virtual void DelegateResponsibility(const MyB& necessaryInfo);
    };
    
    class D: public C
    {
        // Uh-oh- we don't inherit friendship   
        virtual void DelegateResonsibility(const MyB& necessaryInfo);
    };