C++ friend class of the same name in different levels of a nested namespace

201 views Asked by At

Not sure if this is possible, but I have two classes of the same name in different levels of a nested namespace and I'd like to make the more shallow class a friend of the deeper class. Example:

In File1.h:

namespace A
{
  class Foo
  {
    //stuff
  };
}

In File2.h:

namespace A
{
  namespace B
  {
    class Foo
    {
      friend class A::Foo; //Visual Studio says "Error: 'Foo' is not a member of 'A'"
    };
  }
}

Is this possible? If so, what is the proper syntax?

2

There are 2 answers

0
alexeykuzmin0 On

This code compiles ok when placed in one file (except that a ; is necessary after A::B::Foo class): IdeOne example.

So, the issue is in the code not included in the question text. Probably #include "File1.h" was forgotten in File2.h.

0
StoryTeller - Unslander Monica On

If you want to avoid including large header files into others, you need to at least forward declare your classes before using them:

namespace A
{
  class Foo;

  namespace B
  {
    class Foo
    {
      friend class A::Foo;
    }
  }
}