C++ friend function

If a function is defined as a friend function in C++ then the protected and private data of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.


Declaration of friend function in C plus plus

 
  • class class_name  
  • {  
  •     friend data_type function_name(argument/s);  
  • };  

 

C++ friend function Example

Let’s see the simple example of C++ friend function used to print the length of a box.

 
  • #include <iostream>  
  • using namespace std;  
  • class Box  
  • {  
  •     private:  
  •         int length;  
  •     public:  
  •         Box(): length(0) { }  
  •         friend int printLength(Box); //friend function  
  • };  
  • int printLength(Box b)  
  • {  
  •     b.length += 10;  
  •     return b.length;  
  • }  
  • int main()  
  • {  
  •     Box b;  
  •     cout<<“Length of box: “<< printLength(b)<<endl;  
  •     return 0;  
  • }  

Output:

Length of box: 10