Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend functions of a class inside a namespace

I've two question about this code bellow:

namespace A { class window; }

void f(A::window);

namespace A
{
    class window
    {
    private:
       int a;
       friend void ::f(window);
    };
}

void f(A::window rhs)
{
    std::cout << rhs.a << std::endl;
}

1) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?

2) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not defined inside a namespace it's ok for the function to be declared after the function is declared a friend.

like image 497
AlexDan Avatar asked Jun 07 '12 17:06

AlexDan


1 Answers

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).

like image 83
Captain Obvlious Avatar answered Sep 18 '22 10:09

Captain Obvlious