What is Friend Class in C++: Explanation and Example
friend class is a class that is allowed to access the private and protected members of another class. Declaring a class as a friend breaks the usual encapsulation rules, enabling close cooperation between classes.How It Works
Imagine two friends sharing secrets that others can't know. In C++, a friend class is like a trusted friend who can peek inside another class's private parts. Normally, private members of a class are hidden and cannot be accessed from outside. But when a class declares another class as its friend, it allows that friend class to access its private and protected members directly.
This is useful when two classes need to work closely together, sharing details without exposing them to the whole program. The friend class declaration is one-way: the friend can access the private parts of the other class, but not vice versa unless also declared.
Example
This example shows how one class can access private data of another class by being declared a friend.
#include <cstdio> class Box { private: int width; public: Box(int w) : width(w) {} friend class BoxFriend; // Declare BoxFriend as friend }; class BoxFriend { public: void showWidth(Box &b) { // Access private member width directly printf("Width of box: %d\n", b.width); } }; int main() { Box box(10); BoxFriend bf; bf.showWidth(box); return 0; }
When to Use
Use a friend class when two classes need to work very closely and share internal details without exposing them publicly. For example, a helper class might need to access private data of a main class to perform complex operations efficiently.
It is common in operator overloading, where a friend class or function accesses private members to implement operators. However, use friendship sparingly because it breaks encapsulation and can make code harder to maintain if overused.
Key Points
- A friend class can access private and protected members of another class.
- Friendship is not mutual; it must be declared explicitly.
- It helps classes work closely without exposing internals publicly.
- Use friendship carefully to avoid breaking encapsulation.