C++ Friend Functions
Private members are normally only accessible to the class's own member functions. Occasionally a function that is not a member needs that access too. C++ lets a class grant it explicitly by declaring the function a friend.
Declaring a friend function
The class lists the function inside its body with the keyword friend. The function itself is an ordinary free function — it is not called with obj. and has no this pointer:
#include <iostream>
using namespace std;
class Box {
public:
Box(double w, double h, double d) : width(w), height(h), depth(d) {}
friend double volume(const Box& b); // grant access
private:
double width, height, depth;
};
double volume(const Box& b) { // a normal function, not Box::volume
return b.width * b.height * b.depth; // may read private members
}
int main() {
Box crate(2, 3, 4);
cout << "Volume: " << volume(crate) << "\n";
}Volume: 24
Key points:
- Friendship is granted by the class, never taken: a function cannot declare itself a friend of some class.
- It does not matter whether the
frienddeclaration is in thepublicorprivatesection. - Friendship is not inherited and not transitive: a friend of
Ais not automatically a friend of classes derived fromA.
The classic use: operator<<
The most common friend in real code is the stream output operator. It must be a free function because its left operand is the stream (cout << obj), not your object, yet it needs to print the private data:
#include <iostream>
#include <string>
using namespace std;
class Fraction {
public:
Fraction(int n, int d) : num(n), den(d) {}
friend ostream& operator<<(ostream& os, const Fraction& f) {
return os << f.num << "/" << f.den;
}
private:
int num, den;
};
int main() {
Fraction half(1, 2), third(1, 3);
cout << half << " and " << third << "\n";
}1/2 and 1/3
Defining the friend directly inside the class, as above, is a common and tidy shortcut. Operator overloading is covered in its own lesson.
A function friend of two classes
A friend function is handy when an operation naturally involves the private data of two different classes:
#include <iostream>
#include <string>
using namespace std;
class Wallet; // forward declaration
class Person {
public:
explicit Person(string n) : name(n) {}
friend void pay(Person& p, Wallet& w, int amount);
private:
string name;
int purchases = 0;
};
class Wallet {
public:
explicit Wallet(int c) : cash(c) {}
friend void pay(Person& p, Wallet& w, int amount);
private:
int cash;
};
void pay(Person& p, Wallet& w, int amount) {
if (w.cash >= amount) {
w.cash -= amount;
p.purchases++;
cout << p.name << " paid " << amount << ", cash left " << w.cash << "\n";
} else {
cout << p.name << " cannot afford " << amount << "\n";
}
}
int main() {
Person li("Li");
Wallet w(50);
pay(li, w, 20);
pay(li, w, 40);
}Li paid 20, cash left 30
Li cannot afford 40
Friend classes
A whole class can be made a friend. All of its member functions then get access to the private members:
#include <iostream>
using namespace std;
class Engine {
friend class Mechanic; // Mechanic may access everything in Engine
private:
int wear = 73;
void reset() { wear = 0; }
};
class Mechanic {
public:
void service(Engine& e) {
cout << "wear before: " << e.wear << "\n";
e.reset();
cout << "wear after: " << e.wear << "\n";
}
};
int main() {
Engine engine;
Mechanic m;
m.service(engine);
}wear before: 73
wear after: 0
Use friends sparingly
| Good reasons | Warning signs |
|---|---|
Stream operators << and >> |
Making half your program a friend |
Symmetric operators like == or + |
Using friends to avoid designing a proper public interface |
| Tightly coupled helper classes (iterators, builders) | Friend classes in unrelated parts of the codebase |
Note: A friend is part of the class's interface in all but name — it is declared inside the class, after all. Used deliberately, friends do not break encapsulation; they extend it to functions that genuinely belong with the class.
Test yourself
Who decides that a function is a friend of a class?
- The function itself
- The class, by declaring it with
friend - The compiler automatically
- Any derived class
Does a friend function have a this pointer?
- Yes
- No, it is not a member function
- Only if declared public
- Only inside the class body
If B derives from A, and f is a friend of A, is f a friend of B?
- Yes, friendship is inherited
- No, friendship is not inherited
- Only for public members
- Only if B is a struct