Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 171 ยท Object-Oriented Programming

Friend Functions and Classes

Learn C++ friend functions and friend classes - granting private access, friends for operators, hidden friends, tightly coupled classes, and when friendship is a design smell.

Access specifiers draw a line around a class: private members can only be touched by the class's own member functions. That line is what keeps an object's invariants safe (see Access Specifiers and Encapsulation). Occasionally, though, a function that is not a member is still logically part of the class's interface and needs to see its internals. The textbook case is operator<< for printing, which can't be a member because its left operand is a stream, not your object.

C++ lets a class name such functions, and even whole other classes, as friends. A friend gets the same access as a member, without being one. In this lesson you'll learn how to declare friend functions and friend classes, the exact rules friendship follows (it is granted, not taken, and it isn't inherited or transitive), the "hidden friend" idiom used by modern libraries, and how to tell good uses of friendship from shortcuts that weaken encapsulation.

Declaring a friend function

Inside the class, write friend followed by the function's declaration. The function is defined like any free function: no ClassName:: prefix, no this, and it receives objects as ordinary parameters.

C++ A friend function reads private members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few points that trip people up:

  • The friend declaration can go in the public, private or protected section; it makes no difference. Many teams put friends next to the public interface because they are part of it.
  • distance is not a member. You call it as distance(home, shop), not home.distance(shop).
  • Friendship is granted by the class. Code outside can't declare itself a friend of Point; only Point's author can.

Why not just make distance a member? You could, but the symmetric free function reads better and treats both points equally. And for some functions, a member is not an option at all.

Friends for operators

Binary operators whose left operand isn't your class must be free functions. std::cout << p calls operator<<(std::ostream&, const Point&); there is no way to add a member to std::ostream. If the operator needs private data, it becomes a friend.

C++ Printing with a friend operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The function is defined inside the class body. That is legal for friends, and the function is still a free function, not a member. (Negative amounts would need more care; the point here is the friendship.) You'll write the full family of operators, including >>, + and comparisons, in Operator Overloading.

A friend isn't the only way to write operator<<. If the class already has a public way to get what you need, a plain non-friend free function is better, because it depends only on the public interface:

C++
std::ostream& operator<<(std::ostream& out, const Money& m) {
    return out << m.to_string();   // no friendship needed
}

Choose a friend when exposing a public getter just for printing would leak details you'd rather keep private.

Hidden friends

When a friend function is defined inside the class and not declared anywhere else, it is called a hidden friend. Ordinary name lookup can't see it. The compiler finds it only through argument-dependent lookup (ADL), which looks inside the classes of the arguments. In practice that means the function is only considered when at least one argument is of your type.

That sounds like a quirk, but it's a feature:

  • Faster compiles and clearer errors. A program with hundreds of operator<< overloads doesn't make the compiler consider all of them for every <<; it only considers the ones attached to the argument types. Error messages list fewer irrelevant candidates.
  • No surprising conversions. A hidden friend isn't chosen when neither argument is your type, even if both could convert to it.
C++ Hidden friends are found through their arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Hidden friends are the recommended way to define operators for your own types in modern C++. The defaulted operator== above is a C++20 feature you'll meet again in Operator Overloading.

If a non-operator friend is defined inside the class and you want people to call it like a normal function, make sure it takes your class as a parameter. A friend void reset_all() with no class parameter, defined in the class, can't be found by anyone, so it can never be called.

Friend classes

A class can befriend another whole class. Every member function of the friend class then has full access to the granting class's private and protected members.

C++
class Engine {
    friend class Car;        // all of Car's members may use Engine's privates
private:
    int rpm_ = 0;
    void ignite() { rpm_ = 800; }
};

Use this when two classes are designed as one unit and split only for clarity: a container and its iterator, a linked list and its node, a builder and the object it builds, a class and its unit-test helper. Here's a container whose iterator needs private access to walk the storage, while users only see begin() and end():

C++ A container and its friend iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The friendship goes both ways here, and each direction is deliberate: Ring befriends the iterator so it can read the storage, and the iterator befriends Ring so only the container can construct iterators through the private constructor. Neither class exposes anything extra to the rest of the program. You'll learn more about iterator requirements in Iterators.

Friend member functions

Instead of a whole class, you can befriend a single member function of another class: friend void Car::start(Engine&);. It's more precise, but it requires Car to be fully defined before Engine, which often creates awkward ordering problems. Most code uses a friend class or a redesign instead.

The rules of friendship

Friendship is deliberately limited:

Rule Meaning
Granted, not claimed Only the class itself can declare its friends.
Not mutual If A befriends B, B's privates are still closed to A.
Not transitive A friend of your friend is not your friend.
Not inherited Classes derived from a friend get no access; a friend of a base class gets no access to private members a derived class adds.
Not a member A friend function has no this, isn't called with . and isn't affected by const qualifiers on the class.
C++
class Vault {
    friend class Manager;
    int secret_ = 42;
};

class Manager {
public:
    int peek(const Vault& v) const { return v.secret_; }      // OK: Manager is a friend
};

class Intern : public Manager {
public:
    int peek_too(const Vault& v) const { return v.secret_; }  // error: friendship isn't inherited
};

Friend declarations also interact with templates (template <typename T> friend class Wrapper; befriends every instantiation). That's mostly useful when writing generic containers; see Class Templates.

When friendship is appropriate

Friendship is sometimes described as "breaking encapsulation". A better way to see it: a friend is part of the class's implementation, declared in the class itself, so a reader of the class can see every function with private access. It extends the encapsulation boundary to cover a few named outsiders. That's often better than the alternative of adding public getters and setters that anyone can use.

Good uses:

  • Operators that must be free functions (<<, >>, symmetric +, ==), especially as hidden friends.
  • Tightly coupled helper classes designed together: iterators, nodes, builders, handles.
  • Factories and private constructors, when one specific class must create objects nobody else may.

Warning signs:

  • A friend added only to make some unrelated code compile ("it needed the balance, so I made it a friend").
  • Long lists of friend classes, or friends in a different module or library.
  • Friend functions that modify invariants without going through the class's checks.
  • Befriending test classes in production code. It's sometimes pragmatic, but usually means the class does too much or its public behavior is hard to observe. Test through the public interface first.

If you can't explain why a function is part of the class's interface, it shouldn't be a friend.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class declares friend void dump(const Box& b); in its private section. Which statement is true?

    The access section of a friend declaration doesn't matter. dump is an ordinary non-member function that has been granted private access.
  2. 2. Class A declares friend class B;. Class C derives from B. Which of these can access A's private members?

    Friendship is not inherited. B has access because A named it; C is a different class, so it gets nothing even though it derives from B. (A's own members always have access, of course.)
  3. 3. Why must operator<<(std::ostream&, const Money&) be a free function rather than a member of Money?

    For a member operator, the object it's called on is the left operand. In cout << money, the left operand is the stream, so the overload must be a free function, often a friend.
  4. 4. What is special about a hidden friend (a friend function defined only inside the class)?

    Ordinary lookup can't see a hidden friend. ADL finds it through the argument types, which reduces overload sets and avoids accidental conversions.

Summary

  • friend gives a non-member function or another class the same access to private and protected members that the class's own members have.
  • A friend function is a free function: no this, called normally, and the access section of its declaration doesn't matter.
  • Operators whose left operand isn't your class, such as operator<<, are the classic friends.
  • Hidden friends (defined only inside the class) are found through argument-dependent lookup; they're the modern way to define operators.
  • Friend classes suit tightly coupled designs such as containers and their iterators.
  • Friendship is granted by the class and is not mutual, transitive or inherited. Use it to extend encapsulation to a few named helpers, never as a shortcut.

Next: Operator Overloading, where you'll give your classes natural syntax for arithmetic, comparison, printing and indexing.