Topic 60 of 83
Friend Functions
Overview
The `friend` keyword punches a controlled hole in Encapsulation. It allows a specific external function or class to access the `private` and `protected` members of the class granting friendship.
Syntax
cpp
class Data {
private:
int secret = 42;
// Granting friendship to an outside function
friend void revealSecret(Data d);
// Granting friendship to another class
friend class Hacker;
};
void revealSecret(Data d) {
// Can access private 'secret'!
cout << d.secret;
}Common Pitfalls
- Overusing friends completely breaks encapsulation and makes spaghetti code. Only use it when absolutely necessary (like operator overloading or tightly coupled helper classes).
Interview Tips
- Friendship is NOT inherited (your friend's children are not your friends), and it is NOT mutual (if A is a friend of B, B is not automatically a friend of A).
Real-World Example
Using friend functions for operator overloading (like << for cout).
example
cpp
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
// Friend allows the global << operator to read private x and y
friend ostream& operator<<(ostream& os, const Point& p);
};
ostream& operator<<(ostream& os, const Point& p) {
os << "(" << p.x << ", " << p.y << ")";
return os;
}
int main() {
Point p(10, 20);
cout << p << endl; // Prints (10, 20)
return 0;
}