Concept of Friend Function in OOP

A friend keyword is a function which is declared using friend keyword. 

             It is not a member of the class but it has access to the private and protected members of the class. It can not access the member names directly. It can be declared either in public or private part of the class.

            It is not in the scope of the class to which it has been declared as friend. It is not a member of the class so it cannot be called using the object. Usually, it has the objects as arguments.

           It is normal external function which is given special access privileges.

Syntax:

class ABC
{
                 public:
                          ----------------------------
                          friend void xyz (void);    // declaration
                          ----------------------------
};

Example:

#include<iostream>
using namespace std;
class numbers
{
               int num1 , num2;
               public:
                          void setdata (int a, int b);
                          friend int add (numbers N);
};
void numbers :: setdata(int a, int b)
{
             num1=a;
             num2=b;
}
int add(numbers N)
{
             return (N.num1+N.num2);
}
int main()
{
            numbers N1;
            N1.setdata(10,20);
            cout<<"Sum = "<<add(N1);
}

Output:

Sum = 30

             add is a friend function of the class numbers so it can access all members of the class (private, public and protected). Member functions of one class can be made friend function of another class, like...

class X
{
             ------------------------------
             int f();
};
class Y
{
           -------------------------------
           friend int X :: f();
};


                    The function f is a member of class X and a friend of class Y. We can declare all the member functions of one class as the friend functions of another class. In such cases, the class is called a friend class, like class X is the friend class of class Z. 

class Z
{
           -------------------------------
           friend class X;
           -------------------------------
}