2

While compiling the following code:

class A {
    A() = default;
public:
    friend A getA() {
        return A();
    }
};

int main()
{
    A a = getA();
}

The compiler gives me an error:

'getA' was not declared in this scope

Why is that?

michalt38
  • 1,193
  • 8
  • 17
  • While `getA` is not a member function, it's still declared in the scope of the `A` class. Declaring friend function without a declaration to put it in the outer namespace scope is useful when it can be used for [argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl) (which is common for example the output and input operator `<<` and `>>`). But in this case there's simply no `::getA` function. – Some programmer dude Apr 22 '20 at 08:12
  • Why can't I call function getA() in a member function of a class A? If I try to do so compiler says still 'getA' was not declared in this scope. – michalt38 Apr 22 '20 at 11:14

1 Answers1

2

Because the friend function getA can't be found by name lookup.

(emphasis mine)

A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided

getA can't be found by ADL either, (it has no parameters). You need to provide a declaration at the namespace scope. e.g.

class A;
A getA();
class A {
    A() = default;
public:
    friend A getA() {
        return A();
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405