Friend Function in C++
As we know that private data members can only be accessed within a class and not outside it.
Definition: A friend function is capable to access the private/protected data of a class in which it is declared as a friend, though it is a nonmember function of that class
Basic properties of friend
- A function can be declared as a friend to any number of classes
- A friend function tough not a member function has full rights and access to the members of the class
Creating a friend function
using namespace std;
friend void display(demo);//friend function declaration
void display(demo d)//friend function defination
cout<<"a: "<<d.a<<endl;//access of private data
display(d);//calling a friend function
In the above code display() function is made friend with demo class so that display() function can access the private data of the class demo
- A class declared with a friend with another class is able to access private/protected data members of that class
- When a class is made a friend class, all the member functions of that class becomes friend functions to that class
Creating friend class
- In this program, all member functions of class test2 will be friend functions of class test1.
- Thus, any member function of class test2 can access the private and protected data of class test1.
- But, member functions of class test1 cannot access the data of class test2.
using namespace std;
cout<<"enter 2 integers";
friend class test2;//defining friend class
enter 2 integers 3 4
Code reusability: instead of creating separate member functions to access private data of each class ,a single member function can access private data of many classes
security: friend functions should be used only when absolutely necessary because friend mechanism alters the security of private data which is against data hiding
Real-time applications of Friend
- Device integration is possible only by friend
ex: GPRS, Satellite communication
- Friend class is also used in APIs(Application Programming Interface)
ex: money transfer from one bank to another
Java and Unix System never support Friend Mechanism