BCA / B.Tech 12 min read

Friend Class in C++

Friend Class in C++:


In C++, a friend class is a special type of class that is allowed to access the private and protected members of another class. Normally, according to the rules of object-oriented programming in C++, the private and protected members of a class can only be accessed by the member functions of that same class. However, sometimes we need to share specific information between two classes where one class can access the private members of another. In such situations, a friend class is used.

What is a Friend Class?
A friend class is a class that is permitted to access the private and protected members of another class. Normally, any class can only access its own members, but through a friend class, one class can directly access the private and protected data of another.

Declaration of a Friend Class:
Declaring a friend class is very simple. Inside a class, you use the `friend` keyword to declare another class as a friend class.

Advantages of a Friend Class:
  • Strong Relationship Between Classes: It can establish a strong relationship between two classes, useful when data sharing is necessary.
  • Specialized Operations: It allows for specialized operations where access to private members of another class is required.
  • Flexibility in Encapsulation: It helps in accessing data without completely violating encapsulation, as access is limited to the friend class only.

Disadvantages of a Friend Class:
  • Partial Violation of Encapsulation: It partially violates the principle of encapsulation.
  • Increased Complexity: Excessive use can make the code complex.
  • Difficulty in Maintenance: Maintenance can become difficult as multiple classes might depend on each other's private members.

Use of a Friend Class:
A friend class is used in special situations where a close relationship between two or more classes is needed, such as for collaboration between classes or to help in complex data structures.