Learn C++
#include "oopadvanced/friend.hpp"

Friend Functions & Classes in C++

//concept

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.

//how it works
1

Granted inside the class

friend std::ostream& operator<<(std::ostream&, const T&); written inside T gives that one function full private access.

2

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.

3

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.

4

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.

//example
#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;
}
Output
(3,4)
1x and y are private — main and ordinary functions cannot name them.
2The friend operator<< is exempt from access checks, reading p.x and p.y directly to format them.
3cout << p prints (3,4) — printable objects with zero getters added to the public surface.
//use cases
Printable classes via friend operator<< without exposing getters for everything
Iterator/container pairs where the iterator must reach container internals
White-box unit tests granted friend access to verify invariants
Symmetric binary operators (Complex + double and double + Complex) as free functions

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.