Friend function
In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data.
A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods. Friend functions allow alternative syntax to use objects, for instance f(x) instead of x.f(), or g(x, y) instead of x.g(y). Friend functions have the same implications on encapsulation as methods.
A similar concept is that of friend class.
01Use cases
This approach may be used in friendly function when a function needs to access private data in objects from two different classes. This may be accomplished in two similar ways:
- A function of global or namespace scope may be declared as friend of both classes.
- A method of one class may be declared as friend of another one.
Sources and credits
This article is adapted from the Wikipedia article “Friend function”, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.
Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.