Question

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

Was it helpful?

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.

OTHER TIPS

As far as I can see you can not. The reasons:

  1. The “anonymous” namespace is accessible only within the file you created it in.
  2. You have to define whole AnonClass class and it's functions in one namespace, i.e. in one place in the program.
  3. Class A has to be defined before AnonClass constructor.
  4. AnonClass has to be at least declared before class A.

So you see, you can't break AnonClass definition on two parts. And you can't define it both before and after A class.

The only option - put class A into the same anonymous namespace. This code works:

namespace 
{
  class A
  {
   public:
    A():a(0){};
   private:
    int a;

    friend class AnonClass;
  };

  class AnonClass
  {
  public:
    AnonClass(A* parent);
  };

  AnonClass::AnonClass(A* parent)
  {
      parent->a = 0;
  };
}

int main() {
  A a;

  return 0;
}

I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top