I\'ve two question about this code bellow:
namespace A { class window; }
void f(A::window);
namespace A
{
class window
{
private:
int a;
1) because function f
is declared and defined outside of the current namespace. If you moved the definition of your class into the same namespace as the function whether global or otherwise you wouldn't need to.
2) you always need to declare a function before it is referenced. Your class references the function with the friend statement.
As for 1), your function is not in the namespace, so you must use :: to tell the compiler to search it outside the namespace.
Otherwise, it will only look for function inside the namespace (that's why they exist). Koenig lookup doesn't apply here, as window class is inside the namespace.
not too sure about 2) though, but i bet it is related to 1).
When you declare f()
as a friend it's actually done in the enclosing namespace of the containing class (A
in this case) if a forward declaration is not already present.
So this...
namespace A
{
class window
{
private:
friend void ::f(window);
};
}
essentially becomes this...
namespace A
{
class window;
void f(window);
class window
{
private:
friend void f(window);
};
}
Edit: Here is a snippet from the C++ standard that explicltly talks about this scenario:
Standard 7.3.1.2 / 3 :
Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship).