I thought I could do this:
class TestA
{
private:
class Nested
{
};
};
class TestB
{
public:
friend class TestA;
friend class TestA::Nested;
};
But I get an error:
Error C2248 'TestA::Nested': cannot access private class declared in class
Is there a way to befriend private nested class? How do I do it?
I encountered this error when trying to compile an MSVC 6 project in MSVC 2017 (C++17). I guess it worked back then.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
If the declaration of a nested class is followed by the declaration of a friend class with the same name, the nested class is a friend of the enclosing class.
A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With