This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 114a. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-04-18


1699. Does befriending a class befriend its friends?

Section: 11.8.4  [class.friend]     Status: open     Submitter: David Krauss     Date: 2013-06-12     Liaison: EWG

According to 11.8.4 [class.friend] paragraph 2,

Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.

A friend declaration is a member-declaration, but it is not clear how far the granting of friendship goes in a friend declaration. For example:

  class c {
    class n {};
    friend struct s;
  };

  struct s {
    friend class c::n;          // #1
    friend c::n g();            // #2
    friend void f() { c::n(); } // #3
  };

In particular, if a friend function is defined inside the class definition, as in #3, does its definition have access to the private and protected members of the befriending class? Implementations vary on this point.

Additional note (June, 2021):

The initial opinion of CWG (at the September, 2013 meeting) was that “member declarations” was intended to be the English equivalent of the syntactic nonterminal member-declaration, including a friend declaration/definition inside the member-specification of a class, making #3 well-formed. However, recent discussion has expressed concern over the different treatment of in-class and out-of-class definitions of friend functions and observed that there is still divergence among implementations.

Rationale (November, 2021):

There are two lines of analysis that lead to opposite conclusions. The first is that a friend defined within the member-specification is written by the class author and is effectively part of the class, not subject to hijacking by other declarations, and thus should be afforded the same access as all other declarations that are part of the class. The second is that giving different access to a friend function based simply on whether it was defined inside or outside of its befriending class is confusing.

CWG considered this to be a design-level question, not simply to be determined by the usual relationship between English and grammar terms, and thus is asking EWG for its opinion.

Additional note (May, 2023)

Forwarded to EWG via cplusplus/papers#1573.