Question

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?

Was it helpful?

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);
};

OTHER TIPS

You could put your class B in a detail namespace, at file scope.

something like this:

namespace my_hidden_area {
    class B {
        ...
    }
}

It's not as strong protection as making the class nested private, of course, but it should make it clear to outsiders that they should not be messing around with B.

If you're wondering why friendship is not inheritable, see this question: Why does C++ not allow inherited friendship?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top