Friend Functions & Classes in C++
friend selectively opens a class's private interior to one outsider — a function or class named in a friend declaration bypasses access checks. It is the escape hatch for operations that need internals but can't be members, most famously operator<< (the left operand is ostream, so it can't be a member of your class).
Friendship is granted, never taken; neither inherited nor transitive. Overuse rots encapsulation, but a friend operator, test fixture, or tightly-coupled helper (like a linked-list node accessing its container) is idiomatic and honest about the coupling.
Granted inside the class
friend std::ostream& operator<<(std::ostream&, const T&); written inside T gives that one function full private access.
operator<< needs it
std::cout << obj calls operator<<(cout, obj) — a free function, since cout owns the left side — so it must be a friend to read privates.
Not inherited, not transitive
A friend of Base is not a friend of Derived, and friends of friends get nothing — each grant is explicit and narrow.
Keep the circle tiny
One operator, one iterator class, one test suite — if the friend list grows, the design (not the access level) needs rethinking.
#include <iostream> class Point { int x, y;public: Point(int a, int b) : x(a), y(b) {} friend std::ostream& operator<<(std::ostream& o, const Point& p) { return o << "(" << p.x << "," << p.y << ")"; }}; int main() { Point p(3, 4); std::cout << p << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.