How to befriend private nested class
This will do it:
class TestA {
friend class TestB;
private:
class Nested {};
};
class TestB {
public:
friend class TestA::Nested;
};
Explanation: It's TestA
itself that has the responsibility to give access to its internals to others. Imagine any class
could intrusively use friendship to get access to other classes' internals (from libraries etc.), this would open the door to arbitrarily break encapsulation.
Same way you get access to any other private thing. You need friendship the other way:
class TestA
{
friend class TestB; // <== this
private:
class Nested
{
};
};
class TestB
{
public:
friend class TestA;
friend class TestA::Nested; // <== now we're a friend of TestA, so we can access it
};
You're trying to use the private
nested class of TestA
in TestB
, then you should declare TestB
as the friend
in TestA
. e.g.
class TestA
{
private:
class Nested
{
};
friend class TestB; // allow TestB to access the private members of TestA
};