Advantages of Friend Functions
- A friend function is able to access members without the need of inheriting the class.
- The friend function acts as a bridge between two classes by accessing their private data.
- It can be used to increase the versatility of overloaded operators.
- It can be declared either in the public or private or protected part of the class.
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.
Syntax:
friend class class_name; // declared in the base class
Example:
// C++ Program to demonstrate the
// functioning of a friend class
#include <iostream>
using namespace std;
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// friend class declaration
friend class F;
};
// Here, class F is declared as a
// friend inside class GFG. Therefore,
// F is a friend of class GFG. Class F
// can access the private members of
// class GFG.
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}
Output
The value of Private Variable = 10 The value of Protected Variable = 99
Note: We can declare friend class or function anywhere in the base class body whether its private, protected or public block. It works all the same.