Explain in detail the concept of friend function.
SOLUTION....
Friend Function in C++
A friend function is a non-member function that is granted access to the private and protected members of a class by declaring it with the friend
keyword inside that class.
class A { int x; public: A(int v = 0) : x(v) {} friend void foo(A); // foo can access A::x };
Why/when to use
Symmetric operators that shouldn’t be members (e.g.,
operator+
,operator<<
) but need private access.Cooperating classes where a utility needs to inspect internals of multiple classes.
Non-member utilities that conceptually don’t belong to the class interface but require privileged access.
Key properties & rules
A friend is not a member of the class.
Friendship is granted, not taken: it’s declared inside the class.
Friendship is not inherited and not transitive (friends of my friend aren’t my friends).
Access is limited to what’s declared as friend; use sparingly to avoid eroding encapsulation.
You can friend:
a free function
a member function of another class
an entire class (
friend class X;
)
#include <iostream> using namespace std; class Beta; // forward declaration class Alpha { private: int a; public: Alpha(int v = 0) : a(v) {} // Declare free function 'sum' as friend friend int sum(const Alpha&, const Beta&); }; class Beta { private: int b; public: Beta(int v = 0) : b(v) {} // Declare the same free function as friend friend int sum(const Alpha&, const Beta&); }; // Friend function definition (not a member of either class) int sum(const Alpha& x, const Beta& y) { // Can access x.a and y.b even though they are private return x.a + y.b; } int main() { Alpha A(35); Beta B(25); cout << "Sum = " << sum(A, B) << '\n'; return 0; }