C++ friend class and functions
Friend Class
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes.
Consider a scenario in which you forget your hall ticket to your examination in such a situation having a friend who has access to your private drawer can be really helpful similarly a friend class is very useful.
Syntax for friend Class
Like friend class, a friend function can be given a special grant to access private and protected members.
A friend function can either be a global function or a member function of a different class.
Syntax for friend function
Points to remember
- The use of friends should be limited. If we declare too many friends of a class, it lessens the value of encapsulation of separate classes in object-oriented programming.
- Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A.
- Friendship is not inherited.
- The concept of friends is not there in Java.
Friendship and Inheritance
In C++, when we derive a new class from a base class, friendship is not inherited. If a base class has a friend function, then the function doesn’t become a friend of the derived class.
Demonstration of how a friend of base class is not friend of a derived class
We will get an error message because show() which is a friend of base class X tries to access private data of derived class Y.
A simple C++ program to demonstrate friend function of another class