Search code examples
c++namespacesfriendunnamed-namespace

Is it possible to friend a class in an unnamed namespace in C++?


I am porting code from Java to c++ and I'd like to replicate some anonymous functionalities.

In file A.h I have :

class A
{
private:
  int a;

  class AnonClass;
  friend class AnonClass;
};

In file A.cpp I have :

namespace
{
  class AnonClass
  {
  public:
    AnonClass(A* parent)
    {
      parent->a = 0; // This doesn't work, a is not accessible
    }
  }
}

Is it possible to friend a class in an anonymous namespace in C++?

In Java you can declare anonymous classes so it would be very similar. Also it would not expose AnonClass to clients of A.h


Solution

  • Less known alternative is to make class Anon a member class of A. Inside class A you only need a line class Anon; -- no real code, no friend declaration. Note it goes within class A, almost as in Java. In the .cpp file you write all the details about Anon but you put it not in anonymous namespace but withinA::

      class A::Anon { ..... };
    

    You can split declaration and implementation of A::Anon, as usual, just remeber always add A:: to Anon.

    The class Anon is a member of A and as such gets access to all other members of A. Yet it remains unknown to clients of A and does not clutter global namespace.