Friend Function In C++

Introduction

 
In this blog, we are going to discuss the friend function.

We all know private members cannot be accessed from outside the class. That is a non-member function cannot have access to the privacy of the class. However, there could be a situation where we would like two classes to share a particular function. For example, consider a case where two classes, manager and scientist, have been defined. We would like to use a function income_tax() to operate on the objects of both these classes. In such situations, C++ allows the common function of the private data of these classes. Such a function need not be a member of any of these classes.

To make an outside function “friendly” to a class, we have to simply declare this function as a friend of the class as shown below.

  1. Class ABC   
  2. {  
  3.  Friend void xyz(void//declaration   
  4. };  

The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope operator. The functions that are declared as a friend in any number of classes. A friend, although not a member function, has full access rights to the private members of the class. 

A friend function possesses certain special characteristics:
  • It is not in the scope of the class to which it has been declared as a friend
  • Since it is not in the scope class, it cannot be called using the object of that class.
  • It can be involved like a normal function without the help of any object.
  • Unlike member functions, it cannot access the member names directly and has to use an object name dot membership operator with each member's name.
  •  It can be declared either in public or the private part of a class without affecting, it has the objects as arguments.
Example for Friend Function:

  1. #include <iostream>  
  2. Using namespace std;  
  3. Class sample  
  4. {  
  5. Int  a;  
  6. Int b;  
  7. public:  
  8. void setvalue()   
  9. {   
  10.      a=25; b=45;  
  11. }  
  12. friend float mean (sample s);  
  13. };  
  14. float mean(sample s)  
  15. {  
  16. return float(s.a + s.b)/2.0;  
  17. }  
  18. Int main()  
  19. {  
  20. sample x;  
  21. X.setvalue();  
  22. cout << “Mean value”= “<< mean(X) << “\n”;  
  23. Return 0;  
  24. }  
  25.   
  26. The output of the program would be   
  27. Mean value=32.5  

Summary

 
In this blog, we learned about the friend function with a sample program and example. I hope that you find it helpful.
Eat->Code->Sleep->Repeat.