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:
- class sample
- {
- // data members;
- public:
- friend void abc(void);
- };
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:
- #include <iostream>
- using namespace std;
- class Addition
- {
- int a=5;
- int b=6;
- public:
- friend int add(Addition a1)
- {
- return(a1.a+a1.b);
- }
- };
- int main()
- {
- int result;
- Addition a1;
- result=add(a1);
- cout<<result;
- return 0;
- }
Output:
11