skip to content

In C++, what is a hidden friend operator, and why do library authors define operator== and operator<< that way?

level: seniorimportance: should knowfreq 32%

answer

  1. defined inside the class body
  2. friend declarations bind no names
  3. only argument-dependent lookup finds it
  4. smaller candidate sets, shorter errors

basics

~20 s

A hidden friend is a non-member function defined with friend inside a class body. Ordinary and qualified lookup cannot see it; only argument-dependent lookup finds it when the class is an argument, which keeps overload sets small and diagnostics short.

solid answer

~50 s

A **hidden friend** is a friend function **defined inside the class**, for example `friend bool operator==(const Angle&, const Angle&)`. It is a member of the enclosing namespace, but a friend declaration does not bind its name there, so neither unqualified nor qualified lookup (`geo::operator==`) finds it. Only **argument-dependent lookup** does, when the class is an associated class of an argument. That gives three benefits: the operator is not a candidate for every unrelated `==` in the namespace, which keeps overload resolution cheaper and error messages free of irrelevant candidates; conversions to the class apply only when one argument already involves it; and it has private access without a separate declaration. The costs are that you cannot call it qualified or take its address unless you add a namespace-scope declaration, which makes it no longer hidden.

code

cpp · 25 lines
cpp
#include <iostream>

namespace geo {
class Angle {
public:
    constexpr Angle(double radians) : rad_(radians) {}  // implicit on purpose

    // Hidden friends: defined in the class, found only by ADL.
    friend bool operator==(const Angle&, const Angle&) = default;
    friend std::ostream& operator<<(std::ostream& os, const Angle& a) {
        return os << a.rad_ << " rad";
    }

private:
    double rad_;
};
}  // namespace geo

int main() {
    geo::Angle a{1.5};
    std::cout << a << '\n';               // ADL: Angle is an argument
    std::cout << (a == 1.5) << '\n';      // ADL via a; 1.5 converts to Angle
    std::cout << (1.5 == a) << '\n';      // works from either side
    // bool b = geo::operator==(a, a);    // error: qualified lookup cannot see it
}

go deeper

for a junior

Know that a friend function can be defined inside the class body and that operators such as operator<< are often written that way.

for a middle

Explain the lookup rule: the friend belongs to the enclosing namespace but binds no name there, so only argument-dependent lookup finds it.

for a senior

Argue the benefits with evidence: shorter candidate lists in diagnostics, cheaper overload resolution in large namespaces, and conversions limited to calls that involve the class.

for a principal

Decide when a library standardizes on hidden friends for operators and customization functions, weighing lookup hygiene against the need to name or take the address of a function.

## What makes a friend hidden A **friend declaration** inside a class names a non-member function that may access the class's private members. When the friend function is also **defined** inside the class, and nowhere else declared at namespace scope, it is called a **hidden friend**: ```cpp namespace geo { class Angle { public: constexpr Angle(double radians) : rad_(radians) {} // implicit on purpose friend bool operator==(const Angle&, const Angle&) = default; // C++20 friend std::ostream& operator<<(std::ostream& os, const Angle& a) { return os << a.rad_ << " rad"; } private: double rad_; }; } ``` The function belongs to namespace `geo`, yet the standard says friend declarations **do not bind names anywhere**. So: - unqualified lookup inside `geo` does not see it; - qualified lookup does not see it: `geo::operator==(a, b)` fails with clang's `no member named 'operator==' in namespace 'geo'`; - **argument-dependent lookup** does see it, because ADL explicitly includes functions declared as friends of the associated classes of the arguments. In practice the function exists only for calls where an `Angle` (or a type with `Angle` as an associated class) is one of the arguments. ## Why library authors prefer it | Concern | Namespace-scope `operator==` in `geo` | Hidden friend | |---|---|---| | Candidate for `x == y` on unrelated `geo` types | yes, ordinary lookup inside `geo` finds it | no | | Diagnostics for a bad `==` on another type | list it as a non-viable candidate | do not mention it | | Implicit conversions to `Angle` | considered whenever it is a candidate | only when an argument already associates `Angle` | | Access to private members | needs a separate friend declaration | built in | | Callable as `geo::operator==` | yes | no | The candidate-set point matters in big namespaces. A library with hundreds of types, each with a namespace-scope `operator==` and `operator<<`, makes every comparison or stream insertion inside that namespace consider all of them. Each must be checked for viability, which costs compile time, and every failed call prints them all. Compiling `m == n` for a `geo::Mesh` with no `operator==` shows the difference: with a namespace-scope `operator==(Angle, Angle)` in `geo`, clang adds `candidate function not viable: no known conversion from 'Mesh' to 'Angle' for 1st argument`; with the hidden friend, the error is one line. ## Conversions still work where they should Hidden does not mean conversion-free. With the implicit `Angle(double)` constructor above: 1. `a == 1.5` compiles: `a` is an argument, ADL finds the friend, and `1.5` converts to `Angle`. 2. `1.5 == a` compiles for the same reason; with both parameters being function parameters, either side may convert. This works the same before C++20. 3. A comparison between two values of some other type that merely converts to `Angle` does not find the friend, because neither argument associates `Angle`. That third case is the safety benefit: an implicit conversion cannot drag `Angle`'s operators into code that never mentions `Angle`. In C++20, rewritten comparison candidates also let a **member** `operator==` handle `1.5 == a` by reversing the operands, which narrows one historical reason for non-member operators. The hidden friend keeps its lookup benefits regardless. ## Limits and how they are lifted - You cannot name it with a qualifier, take `&geo::operator==`, or pass it as a function pointer. - Declaring the same function again at namespace scope, for example `bool operator==(const Angle&, const Angle&);` in `geo`, makes it visible to ordinary and qualified lookup, and then it is no longer hidden. - A hidden friend defined in a class template is instantiated per specialization, which is how class templates provide operators without separate function templates. ## The interview answer - Defined inside the class with `friend`, found only by argument-dependent lookup. - Keeps operators out of unrelated overload sets, shortening compile times and diagnostics. - Lets conversions apply only when the class is involved, and grants private access for free. - Trade-off: not callable qualified and not addressable unless redeclared outside.

  • How can you make a hidden friend callable as geo::operator== when you need its address?
    Add a matching declaration at namespace scope in geo, such as bool operator==(const Angle&, const Angle&);. That declaration binds the name in geo, so qualified lookup and taking the address work, but it also returns the function to ordinary lookup inside geo, giving up the smaller overload sets.
  • Why is the hidden friend a natural way to give a class template its operators?
    A friend defined inside a class template is instantiated with each specialization, as an ordinary non-template function taking that specialization's type. Its parameters then allow implicit conversions, unlike a free function template whose deduction ignores conversions, and it is found by ADL whenever the specialization is an argument.

  • A friend function defined in a class becomes a member function of that class
  • Hidden friends can be called with a qualified name like geo::operator==
  • Hidden friends never allow an implicit conversion on either argument
  • Hidden friends exist only to get access to private members
  • Defining operators as hidden friends hides them from argument-dependent lookup too

Assumes C++20 for the defaulted operator== and rewritten comparison candidates; hidden-friend lookup itself behaves the same since C++98.