Friend function in C++ Programming

In C++, private members remain hidden and can only be accessed by other member function of that class and friend function. Friend function is defined or declared using keyword ‘friend’ before the function prototype inside the class. It takes objects as parameter and access their private members using object name and dot(.) operator. Friend function is used when we need to operate on data of two or more objects of same or different classes. For e.g. user may need to add the sales of two or more goods or compare the marks of two or more students. In such cases, friend function acts as a bridge for two or more objects.

An example of using friend function to access private member of an object is shown below:

#include <iostream>
#include <conio.h>

using namespace std;

class example
{
  private:
    int a;
  public:
    void getdata()
    {
        cout <<"Enter value of a:";
        cin >>a;
    }
    friend void findmax(example, example);
/* Declaring friend function inside class */
};

void findmax(example e1, example e2)    
/* Defining friend function */
{
    if (e1.a > e2.a)
/* Accessing private members */
        cout <<"Data of object e1 is greater";
    else if (e1.a < e2.a)
        cout <<"Data of object e2 is greater";
    else
        cout <<"Data of object e1 and e2 are equal";
}

int main()
{
    example e1, e2;
    cout <<"Enter data for e1"<<endl;
    e1.getdata();
    cout <<"Enter data for e2"<<endl;
    e2.getdata();
    max(e1, e2);    
/* Calling friend function */
    getch();
    return 0;
}

Outputs:

Enter data for e1
a = 7
Enter data for e2
a = 4
Data of object e1 is greater
Enter data for e1
a = 9
Enter data for e2
a = 13
Data of object e2 is greater
Enter data for e1
a = 14
Enter data for e2
a = 14
Data of object e1 and e2 are equal

Properties of friend function:

  1. It can’t be called using object like other member function.
  2. It is called like normal functions in C or C++.
  3. Private member can be accessed inside friend function using object name and dot(.) operator.
  4. It can take multiple objects as parameter as required.
  5. It should be declared in all the classes whose objects are sent as parameter.
  6. It can be declared or defined in private, public or protected section of a class.