Search code examples
c++classlanguage-lawyerfriendaccess-rights

Why can't a PRIVATE member function be a friend function of another class?


class x
{
    void xx() {}
};

class y
{
    friend void x::xx();
};

This results in an error like

error: friend function 'xx' is a private member of 'x'

Why can't I declare a private member function to be a friend of another class?


Solution

  • [class.friend]/9:

    A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration.

    The reason is quite simple; private members shall obey a clear and definite rule:

    A member of a class can be

    • private; that is, its name can be used only by members and friends of the class in which it is declared.

    Allowing private members to be named in declarations inside unrelated classes would violate this rule: it enables another class to depend on an implementation detail without being explicitly allowed to. This becomes problematic, for instance, when changing a private member's name, type or signature, or removing it entirely; that's intended not to break the interface of that class.

    This can be circumvented by making the entirety of x a friend of y:

    class x {
        void xx() {}
    };
    
    class y {
        friend x;
    };
    

    Demo.