![]() |
VOOZH | about |
In C++, friend functions and friend classes are concepts that allow certain functions or classes to access the private and protected members of another class.
A friend class can access private and protected members of other classes in which it is declared as a friend.
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.
Like friend classes, a friend function can be granted special access to private and protected members of a class in C++. They are not the member functions of the class but can access and manipulate the private and protected members of that class for they are declared as friends.
A friend function can be:
We can declare any global function as a friend function. The following example demonstrates how to declare a global function as a friend function in C++. The keyword "friend" is placed only in the function declaration of the friend function and not in the function definition or call.
Example
Private Variable: 10 Protected Variable: 99
In the above example, we have used a global function as a friend function. A friend function can be declared in any section of the class i.e. public or private or protected.
We can also declare a member function of another class as a friend function in C++. Forward declaration of the class is needed if we want to make a member function of another class a friend inside that class.
Example
Private Variable: 10 Protected Variable: 99
Note: The order in which we define the friend function of another class is important and should be taken care of. We always have to define both the classes before the function definition. Thats why we have used out of class member function definition.
35
| Advantages | Disadvantages |
|---|---|
| Access private and protected members without inheritance | Violates data hiding by exposing private members |
| Enable controlled data sharing between classes | Breaks encapsulation when overused |
| Useful for operator overloading flexibility | Do not support runtime polymorphism |
| Can be declared in any access section of a class | Friendship is not inherited by derived classes |