What can a friend function access in a C++ class? Identify the correct scope of access granted by friendship.

Difficulty: Easy

Correct Answer: All of the above.

Explanation:


Introduction:
Friendship in C++ is a targeted access control escape hatch. This question checks whether you know the breadth of access a friend function receives once declared by a class.


Given Data / Assumptions:

  • A class explicitly declares a function (or class) as friend.
  • We discuss access rights, not ownership or lifetime.
  • Friendship is not inherited or transitive unless redeclared.


Concept / Approach:
A friend function has full access to the class’s private, protected, and public members. Friendship grants access privileges equivalent to those of member functions for the purpose of reading/modifying members, but the friend is still not a member of the class.


Step-by-Step Solution:
1) Inside the class, add ”friend ReturnType f(…);”.2) The named function f can now read/write private and protected members.3) No other unrelated functions gain access unless also declared as friends.4) Derived classes do not automatically become friends.


Verification / Alternative check:
Try compiling code where a friend function writes a private field; it compiles, while a non-friend/non-member attempt fails.


Why Other Options Are Wrong:
Public only: too restrictive—friendship includes private/protected.Protected only / Private only: incomplete; friendship includes all.


Common Pitfalls:
Overusing friendship harms encapsulation. Prefer narrow interfaces; use friends sparingly for operator overloads or factory helpers that need intimate access.


Final Answer:
All of the above.

More Questions from OOPS Concepts

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion