PREV NEXT
What is Friend Function?
- The functions can be defined somewhere in the program just like a normal function but friend function is defined outside the class but it can still access all the private and protected members of the class.
- If we define a function as a friend function, then the protected and private data of a class can be accessed using the function.
- The friend can be a function, a function template or member function, a class or a class template where the entire class and all the members of the class are friends.
- It is easy to declare the friend function. The keyword friend is used while declaring the friend function.
Synatx for declaring the friend function:
class class_name
{
friend data_type function_name() ;
…
}
Friend function example:
Let us have a look at the example to better understand the friend function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <iostream> using namespace std; class Shape { double area; public: friend void printArea( Shape shape ); // friend function void setArea( double ar ); }; // member function void Shape::setArea( double ar ) { area = ar; } // printArea() is not a member function of any class. void printArea( Shape shape ) { /* Because printArea() is a friend of Shape, it can directly access any member of this class */ cout << "Area of shape : " << shape.area <<endl; } // Main function int main() { Shape shape; // set shape area without member function shape.setArea(20.0); // using friend function to print the area. printArea( shape ); return 0; } |
In the above program, the friend fucntion printArea( ) is declared inside Shape class. So, the private data can be accessed from this function.
Some points to Remember:
- Friend function can be invoked like a normal function without the help of any object.
- It cannot access the member names directly and to access them it has to use object name and dot operator with each member name (B.x).
- Friend function can be declared either in public or private class.
Friend Class
- The friend class can access the private and protected members of other class in which it is declared as friend.
- It is also useful to allow a particular class to access the private members of other class.