C++ The Friend Keyword

C++ Tutorial

🤝 C++ friend Keyword

The friend keyword in C++ allows a function or another class to access the private and protected members of a class.
It is used when two or more entities need to work closely together.


🔹 1. Why Use friend?

Normally:

  • private members → accessible only inside the class

  • protected members → accessible in derived classes

Using friend:

  • You can grant special access without making data public

  • Helps in operator overloading, tight coupling, and utility functions


🔹 2. Friend Function

A friend function is not a member of the class, but it can access private data.

Example


 

Usage:

int main() {
Box b(10);
showLength(b);
}

🔹 3. Friend Function Characteristics

  • Declared inside the class

  • Defined outside the class

  • Not called using object (. or ->)

  • Has access to private and protected members


🔹 4. Friend Class

A friend class can access all private and protected members of another class.

Example

class A {
private:
int x = 10;
friend class B; // B is a friend
};class B {
public:
void show(A a) {
cout << a.x; // allowed
}
};


🔹 5. Friend Function of Multiple Classes

class B;

class A {
private:
int x = 5;
friend void show(A, B);
};

class B {
private:
int y = 10;
friend void show(A, B);
};

void show(A a, B b) {
cout << a.x + b.y;
}


🔹 6. Friend and Encapsulation

  • friend breaks strict encapsulation

  • But provides controlled access

  • Should be used carefully and sparingly


🔹 7. Friend and Operator Overloading (Common Use)


 


🔹 8. Important Rules

✔ Friendship is not inherited
✔ Friendship is not transitive
✔ Friendship is not mutual

// If A is friend of B
// B is NOT automatically friend of A

❌ Common Misunderstandings

friend void fun(); // ❌ friend keyword cannot be used in main()

Friend declarations must be inside a class.


🔁 Friend vs Public Members

FriendPublic
Selective accessOpen access
ControlledLess secure
Used for special casesGeneral access

📌 Summary

  • friend allows access to private/protected members

  • Can be function or class

  • Commonly used in operator overloading

  • Breaks encapsulation if misused

  • Use only when necessary

You may also like...