thewalrusnp
thewalrusnp

Reputation: 427

Friend within private nested class

I have two private nested classes that would need to access a private member in another class. I thought about putting the class that needs to access the private member as friend in the accessed class, however I'm getting an error that A::m_nData is private so I can't access it. Anyway of telling the compiler that I need to access the A::m_nData private member within D::DoSomething()?

Here is a sample of what I'm trying to do:

File A.h

class A
{
    class D;

    public:
        A();
        ~A() {}

    private:
        friend class D;

        int m_nData;
};

File A.cpp:

#include "A.h"
#include "B.h"

A::A()
:   m_nData(0)
{
}

File B.h:

#include "A.h"

class B
{
    public:
        B() {}
        ~B() {}

    private:
        class C
        {
            public:
                C(A* pA): m_pA(pA) {}
                virtual ~C() {}
                virtual void DoSomething() {}

            protected:
                A* m_pA;
        };

        class D: public C
        {
            public:
                D(A* pA): C(pA) {}
                virtual ~D() {}
                virtual void DoSomething()
                {
                    m_pA->m_nData++;
                };
        };
};

Upvotes: 1

Views: 5941

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63775

You need two friendships here. One to let A know about the private B::D and another to let B::D access private data in A.

Declare (include) class B before declaring class A.

Then in class B, add:

friend class A;

This allows class A to know about the private B::D.

Then in class A, replace:

friend class D;

with:

friend class B::D;

Upvotes: 2

Related Questions