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 instead of x.f, or g instead of x.g. Friend functions have the same implications on encapsulation as methods.
A similar concept is that of friend class.

Use 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

  1. include
using namespace std;
class Foo; // Forward declaration of class Foo in order for example to compile.
class Bar ;
class Foo ;
// Definition of a member function of Bar; this member is a friend of Foo
void Bar::show
// Friend for Bar and Foo, definition of global function
void show
int main