Search code examples
c++friend

Friend function scope and point of declaration


I've written the simple program:

#include <stdio.h>

class A
{
    friend void foo() { printf("asd\n"); }
};

int main()
{
    A::foo();//fail, foo is not a member of A
}

How can I invoke this friend function defined inside the class body? Also I would like to know what is the point of declaration and scope of friend function.


Solution

  • First of all to declare a friend function do

    class A
    {
        friend void foo();
    };
    

    and define the function outside of the class

    void foo { printf("asd\n"); }
    

    It will be called as any other normal function

    int main() {
        foo();
    }
    

    The point is, that the friend declaration in class A allows foo() access to any internal (private or protected) members of this class.

    To additionally clarify: It is possible to define the function body at the point of the friend declaration, but it's still to be called as shown.