C++ friendship: which statement correctly describes valid use of the friend keyword inside a class?
-
AA private data member can be declared as a friend.
-
BA class may be declared as a friend.
-
CAn object may be declared as a friend.
-
DWe can use friend keyword as a class name.
Answer
Correct Answer: A class may be declared as a friend.
Explanation
Introduction / Context:Friendship in C++ is an access-control feature that allows a specified function or class to access the private and protected members of another class. It is commonly used to implement symmetric operators, tight collaborations between classes, or non-member helper functions that require privileged access without making data public.
Given Data / Assumptions:
- friend grants access to named functions or entire classes, not to specific data members.
- Friendship is neither inherited nor transitive.
- Keywords cannot be reused as identifiers.
Concept / Approach:
Inside a class definition, you can declare either a specific function or another class as a friend. Doing so gives the friend full access to private/protected members of the declaring class. You cannot declare a particular data member as a friend; access always targets functions or whole classes. Friendship is to types or functions, not specific object instances, so “an object as a friend” is meaningless. Finally, the token friend is a reserved keyword and cannot be used as a class name.
Step-by-Step Solution:
Option A → invalid: data members cannot be friends. Option B → valid: friend class Logger; is legal. Option C → invalid: friendship is not per-object. Option D → invalid: friend is a reserved keyword.Verification / Alternative check:
Create two classes and declare one as friend of the other. Access private fields in the friend class's methods; it compiles. Attempt to mark a single data member as friend or to friend an object variable; the compiler rejects these constructs.
Why Other Options Are Wrong:
Private data member as friend — syntactically and semantically unsupported.
Object as friend — friendship is granted to functions or classes, not instances.
friend as class name — violates the reserved keyword rule.
Common Pitfalls:
- Overusing friendship instead of designing clearer public interfaces.
- Expecting friendship to be inherited down the hierarchy; it is not.
Final Answer:
A class may be declared as a friend.