- 2068 Chaitra · 2+3 marks
Friend class and encapsulation
Short answer
A friend function is a non-member given access to private members by a class declaration with friend. A friend class grants all its member functions access to another class's private members. Friends loosen encapsulation but do not violate it because the class itself decides who is a friend; however, excessive use reduces data hiding.
What do you mean by friend function and friend class? Do friends violate encapsulation?
Friend function
A friend function is a non-member function that is given permission, by the class, to access its private and protected members. It is declared inside the class with the keyword friend.
class Box
{
int w;
public:
Box(int x) { w = x; }
friend void show(Box b); // friend function
};
void show(Box b) { cout << b.w; }
Friend class
A friend class is a class all of whose member functions can access the private and protected members of another class. It is declared in the second class as friend class A;. Friendship is not mutual (if A is a friend of B, B is not automatically a friend of A) and not inherited.
Do friends violate encapsulation?
Not really, though they loosen it. Reasons:
- The class itself decides who is its friend, by writing the declaration inside the class. Outsiders cannot grant themselves access.
- Friends are listed in the class definition, so they are part of the class's public interface and are easy to find.
- Without friends we would have to make data public or add many get/set functions, which weakens encapsulation more.
However, a friend can read and change private data directly, so too many friends reduce data hiding and make the code harder to maintain. Friends should be used sparingly, only where closely related classes or operators need them.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Member function as friend of another class · Object Oriented Programming, chapter 4
- Need of friend function · Object Oriented Programming, chapter 4 · asked 2×
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- mdistance and edistance addition via friend · Object Oriented Programming, chapter 4
- Pure virtual function and abstract class · Object Oriented Programming, chapter 7 · asked 5×
- LandMeasure class and sum function · Object Oriented Programming, chapter 4
- Contractor friend's dinner and guesthouse offer · Engineering Professional Practice, chapter 7
- Consultant's friend supplies material; community objects · Engineering Professional Practice, chapter 7
- Event management system summary and class diagram · Object Oriented Analysis and Design, chapter 2