Šimon Tóth
Šimon Tóth

Reputation: 36451

Scope of friend function in GCC

According to the standard:

A friend function defined in a class is in the (lexical) scope of the class in which it is defined.

Then why the heck doesn't this work (several versions of GCC tested)?

#include <iostream>
using namespace std;

class A
{
  friend void function() { cout << "text" << endl; };
};

// void function();

int main()
{
  function();
  return 0;
}

Uncommenting the declaration of course solves the problem.

Edit (gcc output):

(xterm) $ g++ -ansi -pedantic -Wall -Wextra test.cpp 
test.cpp: In function ‘int main()’:
test.cpp:13:11: error: ‘function’ was not declared in this scope

Upvotes: 2

Views: 1663

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507115

The quote means that the following works - the code is in the lexical scope of the class, such that unqualified name lookup will behave specially

class A
{
  typedef int type;

  friend void function() { 
    type foo; /* type is visible */ 
  };
};

If you had defined "function" in the namespace scope, then "type" would not be visible - you would have to say "A::type". That's why it says in the next sentence "A friend function defined outside the class is not.". Unqualified name lookup for an in-class definition is stated as

Name lookup for a name used in the definition of a friend function (11.4) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions. If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions.

So the text you quoted is not really required to be normative - the specification of unqualified name-lookup already covers it.

Upvotes: 3

Related Questions