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.
- Class ABC
- {
- Friend void xyz(void)
- };
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:
- #include <iostream>
- Using namespace std;
- Class sample
- {
- Int a;
- Int b;
- public:
- void setvalue()
- {
- a=25; b=45;
- }
- friend float mean (sample s);
- };
- float mean(sample s)
- {
- return float(s.a + s.b)/2.0;
- }
- Int main()
- {
- sample x;
- X.setvalue();
- cout << “Mean value”= “<< mean(X) << “\n”;
- Return 0;
- }
-
- The output of the program would be
- 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.