Search code examples
c++c++17friend

How to befriend private nested class


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.


Solution

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