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?
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?
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();
}
};