friend (C++)

Resources

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 the friend declaration is independent of the access specifiers (public, private, or protected), so it doesn’t really matter.

Source on Stackoverflow.

class Rational {
	int num, denom;
	... 
	friend istream& operator>>(istream& in, Rational& r);
}
  • the friend gives permission for the function to access any private fields and methods of Rational

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/