Define friend function.

Friend function acts as a friend of the class. It can access the private and protected members of the class. The friend function is not a member of the class, but it must be listed in the class definition. The non-member function cannot access the private data of the class. Sometimes, it is necessary for the non-member function to access the data. The friend function is a non-member function and has the ability to access the private data of the class.

To make an outside function friendly to the class, we need to declare the function as a friend of the class as shown below:

  1. class sample  
  2. {  
  3.    // data members;  
  4.  public:  
  5. friend void abc(void);  
  6. };  

Following are the characteristics of a friend function:

  • The friend function is not in the scope of the class in which it has been declared.
  • Since it is not in the scope of the class, so it cannot be called by using the object of the class. Therefore, friend function can be invoked like a normal function.
  • A friend function cannot access the private members directly, it has to use an object name and dot operator with each member name.
  • Friend function uses objects as arguments.

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. class Addition  
  4. {  
  5.  int a=5;  
  6.  int b=6;  
  7.  public:  
  8.  friend int add(Addition a1)  
  9.  {  
  10.      return(a1.a+a1.b);  
  11.  }  
  12. };  
  13. int main()  
  14. {  
  15. int result;  
  16. Addition a1;  
  17.  result=add(a1);  
  18.  cout<<result;  
  19. return 0;  
  20. }  

Output:

11