Search code examples
c++friend

Friend function and implementation


I came across the following code

class ExDer1 : public ExBase
{
public:
    friend int Der1Fn()
    {
        ....
    }
};

I am a little confused here with

        friend int Der1Fn()
        {
            //This has an implementation .Why is it a friend then ? since it can access the private/protected variables of the ExDer1  class ?
        }

Normally I would expect to see something like the following

friend int Der1Fn(); //No implementation. Indicating that the Der1Fn is a method outside this class

which basically would mean that a function int Der1Fn() would access the private variables of the class ExDer1. However this has an implementation. Could any one please explain what this means ?

Update:

So if I have the following code

class ExDer1 : public ExBase
{
public:
    friend int Der1Fn()
    {
        std::cout << "Hello World";
    }
};

int main()
{
    Der1Fn(); // error C3767: 'Der1Fn': candidate function(s) not accessible
    //.....
}

How do I call Der1Fn ?


Solution

  • Friend function ( or class) can be defined outside or inside class as well. If you define it inside you should provide matching declaration in correct scope, or argument dependent lookup will take place.

    Following examples are logically same:

    Example 1:

    int Der1Fn();
    
    class ExDer1 : public ExBase
    {
    public:
        friend int Der1Fn()
        {
            ....
        }
    };
    

    Example 2 (recommended):

    int Der1Fn()
    {
        ....
    }
    
    class ExDer1 : public ExBase
    {
    public:
        friend int Der1Fn();
    };
    

    How do I call Der1Fn ?

    As simle as this.