0
What is a Friend function in C++?Please explain in an easy way :')
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.