C++ Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.
Declaration of friend function in C++
In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.
Characteristics of a Friend function:
C++ friend function Example
Let's see the simple example of C++ friend function used to print the length of a box.
Length of box: 10
Let's see a simple example when the function is friendly to two classes.
In the above example, min() function is friendly to two classes, i.e., the min() function can access the private members of both the classes A and B.
C++ Friend class
A friend class can access both private and protected members of the class in which it has been declared as friend.
Let's see a simple example of a friend class.
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A. Class B can access the private members of class A.