A friend declaration grants a specific function or class access to a class's private members — a controlled exception to encapsulation.
Friend function
#include <iostream>
class Fraction {
int num_, den_;
public:
Fraction(int n, int d) : num_(n), den_(d) {}
friend std::ostream& operator<<(std::ostream& os, const Fraction& f) { // hidden friend
return os << f.num_ << '/' << f.den_;
}
friend Fraction operator*(const Fraction& a, const Fraction& b) {
return {a.num_ * b.num_, a.den_ * b.den_};
}
friend bool sameValue(const Fraction& a, const Fraction& b);
};
bool sameValue(const Fraction& a, const Fraction& b) { // defined outside, still a friend
return a.num_ * b.den_ == b.num_ * a.den_;
}
int main() {
Fraction half(1, 2), third(1, 3);
std::cout << half * third << ' ' << sameValue(half, Fraction(2, 4)) << '\n';
}1/6 1Friend class
#include <iostream>
class Engine {
int rpm_ = 0;
friend class Mechanic; // Mechanic may touch Engine's privates
};
class Mechanic {
public:
static void tune(Engine& e, int rpm) { e.rpm_ = rpm; }
static int read(const Engine& e) { return e.rpm_; }
};
int main() {
Engine e;
Mechanic::tune(e, 3000);
std::cout << Mechanic::read(e) << '\n';
}3000Friendship is granted, not taken — the class decides who its friends are.
It's not symmetric (A friend of B doesn't make B a friend of A), not transitive, and not inherited.
A hidden friend (defined inside the class) is found only by argument-dependent lookup — the preferred way to write operators.
Does friend break encapsulation?