Why does a C++ friend class need a forward declaration only in other namespaces?

C++ Standard ISO/IEC 14882:2003(E) Namespace member definitions

Paragraph 3

Every name first declared in a
namespace is a member of that
. If a friend declaration in
a non-local class first declares a
class or function
(this implies that the name of the class or function is unqualified) the friend class
or function is a member of the
innermost enclosing namespace.

// Assume f and g have not yet been defined.
void h(int);
template <class T> void f2(T);
namespace A {
   class X {
   friend void f(X);  //  A::f(X) is a friend
      class Y {
         friend void g();  //  A::g is a friend
         friend void h(int);  //  A::h is a friend
         //  ::h not considered
         friend void f2<>(int);  //  ::f2<>(int) is a friend
   //  A::f, A::g and A::h are not visible here
   X x;
   void g() { f(x); }  // definition of A::g
   void f(X) { /* ... */}  // definition of A::f
   void h(int) { /* ... */ }  // definition of A::h
   //  A::f, A::g and A::h are visible here and known to be friends

Your friend class BF; is a declaration of A::BF in namespace A rather than global namespace. You need the global prior declaration to avoid this new declaration.

Leave a Comment