Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to befriend private nested class

Tags:

c++

c++17

friend

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.

like image 907
Tomáš Zato - Reinstate Monica Avatar asked Jul 09 '19 10:07

Tomáš Zato - Reinstate Monica


People also ask

Can nested classes access private members?

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.

Are nested classes friends?

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.

Can nested classes access private members C#?

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.


1 Answers

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
};
like image 167
Barry Avatar answered Oct 07 '22 20:10

Barry