C++ The Friend Keyword

🤝 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:
privatemembers → accessible only inside the classprotectedmembers → 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:
🔹 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
🔹 5. Friend Function of Multiple Classes
🔹 6. Friend and Encapsulation
friendbreaks strict encapsulationBut 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
❌ Common Misunderstandings
Friend declarations must be inside a class.
🔁 Friend vs Public Members
| Friend | Public |
|---|---|
| Selective access | Open access |
| Controlled | Less secure |
| Used for special cases | General access |
📌 Summary
friendallows access to private/protected membersCan be function or class
Commonly used in operator overloading
Breaks encapsulation if misused
Use only when necessary
