friend (C++)
Resources
- https://www.mygreatlearning.com/blog/friend-functions-in-cpp
- https://cplusplus.com/doc/tutorial/inheritance/
Where to declare the
friend?I see usually putting it under
public, although in CS247, we just put it outside of the access specifiers (therefore private). The placement of thefrienddeclaration is independent of the access specifiers (public,private, orprotected), so it doesn’t really matter.Source on Stackoverflow.
class Rational {
int num, denom;
...
friend istream& operator>>(istream& in, Rational& r);
}- the
friendgives permission for the function to access any private fields and methods ofRational
Warning
In general: be cautious when using friends, weakens Encapsulation. Only make friend (C++)s if they can do something for you! Learned in CS247.
Access
In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to
friends. https://cplusplus.com/doc/tutorial/inheritance/