Friend Function in C++
Friend Function
On this page we will discuss about friend function in C++ .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 .A function can be declared as a friend to any number of classes.
Friend Function in C++
Basic Properties of Friend Function in C++
- 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
Run
Output:
#include <iostream> using namespace std; class demo { private: int a=5; friend void display(demo);//friend function declaration }; void display(demo d)//friend function defination { cout<<"a: "<<d.a<<endl;//access of private data } int main() { demo d; display(d);//calling a friend function return 0; }
a:4In the above code display() function is made friend with demo class so that display() function can access the private data of the class demo.
Friend class
- 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.
#include <iostream> using namespace std; class test1 { int a,b; public: void get() { cout<<"enter 2 integers";
cin>>a>>b; } friend class test2;//defining friend class }; class test2 { test1 t1; public: void put() { t1.get(); cout<<"a: "<<t1.a<<endl; cout<<"b: "<<t1.b<<endl; } }; int main() { test2 t2; t2.put(); }
Output:
enter 2 integers 3 4 a:3 b:4
Advantages
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
Disadvantages
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
Note:
Java and Unix System never support Friend Mechanism
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment