What is a Friend function in C++?Please explain in an easy way :') | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is a Friend function in C++?Please explain in an easy way :')

26th Aug 2017, 7:43 AM
Himanshu Pandey
Himanshu Pandey - avatar
2 Answers
+ 2
If you have class X{ private: int secret; } and a function int getSecret(X& x){ return x.secret; } this program will error, because 'secret' is private. The solution is to define 'getSecret' as a friend. class X{ private: int secret; public: friend int getSecret(X&); } Now the function getSecret (and only getSecret) can access all the private members. In my opinion there's never a good reason to use friend functions, so try to not use them too often.
26th Aug 2017, 7:59 AM
Schindlabua
Schindlabua - avatar