Search code examples
c++friend

Why can't forward declared friend class be referred in the class?


The following code doesn't compile:

struct X {
  friend class Y;
  Y* ptr;
};

The cppreference describes the situation as

... If the name of the class that is used in the friend declaration is not yet declared, it is forward declared on the spot.

If the "spot" means where the friend relationship is declared, then it should be fine to declare the member Y* ptr. Why doesn't it compile? Where in the standard prohibits this?


Solution

  • This is a mistake on the site. It contradicts the standard, which says that friendship declaration is not a substitute for a forward declaration:

    7.3.1.2.3 Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class, function, class template or function template the friend is a member of the innermost enclosing namespace. The friend declaration does not by itself make the name visible to unqualified lookup or qualified lookup.

    The part about the name not being visible to unqualified or qualified lookup essentially means that the name does not behave like a forward declaration.