skip to content

In C++, what exactly does a friend declaration grant, and to which code does that access not extend?

level: middleimportance: should knowfreq 48%

answer

  1. one named function or class
  2. the granting class decides
  3. not inherited, not transitive
  4. not reciprocal either
  5. placement under private irrelevant

basics

~20 s

A friend declaration lets one named function or class use the granting class's private and protected members. The grant is exact: not inherited, not transitive, not reciprocal, and the same whether declared under public or private.

solid answer

~40 s

`friend void dump(const Cache&);` or `friend class CacheInspector;` inside `Cache` lets that function, or every member of that class, name `Cache`'s private and protected members. The class doing the granting decides; nobody can declare themselves a friend of someone else. The standard states that friendship is neither inherited nor transitive: a class derived from `CacheInspector` gets nothing, a friend of `CacheInspector` gets nothing, and `Cache` gains no access to `CacheInspector`'s privates. Where the declaration sits, under `public:` or `private:`, does not change its meaning. Related and often confused: access is checked per class, not per object, so a `Cache` member function can already read another `Cache` object's private members without any friend. Typical legitimate uses are operators that need both operands converted symmetrically and tightly coupled pairs such as a container and its iterator.

code

cpp · 26 lines
cpp
#include <cstdio>

class Cache {
public:
    explicit Cache(int capacity) : capacity_(capacity) {}
    bool sameCapacity(const Cache& other) const {
        return capacity_ == other.capacity_;   // OK: access is per class, not per object
    }
    friend class CacheInspector;                 // grants access to one named class
    friend void dump(const Cache& c);            // and to one named function
private:
    int capacity_;
};

class CacheInspector {
public:
    static int capacity(const Cache& c) { return c.capacity_; }
};

void dump(const Cache& c) { std::printf("capacity=%d\n", c.capacity_); }

int main() {
    Cache a(16), b(16);
    dump(a);
    std::printf("%d %d\n", a.sameCapacity(b), CacheInspector::capacity(b));
}

go deeper

for a junior

Recall that a friend function or class may use the private members of the class that names it, and that the class itself grants it.

for a middle

Explain the three negatives, not inherited, not transitive, not reciprocal, and that access is per class so other objects' privates are already reachable.

for a senior

Judge when friend is honest, for symmetric operators and coupled pairs, and when it hides a design problem such as tests needing private access.

for a principal

Set guidance for friend use in public library headers, where each friend extends the set of code that must change together with the class's private data.

## What friend grants C++ access control works on **names**: a private member's name may be used only by the members of its class and by the class's **friends**. A friend declaration, written inside the class that grants access, names who those friends are: - `friend void dump(const Cache& c);` lets the non-member function `dump` use `Cache`'s private and protected members. - `friend class CacheInspector;` lets every member function of `CacheInspector` do the same. - A friend function **defined** inside the class body is a special case with unusual name-lookup rules, covered with namespaces and argument-dependent lookup. The grant is one-directional and controlled by the class that owns the private data. There is no syntax for a function to claim friendship of a class it does not control, which is why friendship is often described as extending the class's interface rather than breaking encapsulation: friends, like members, are listed in the class definition. ## Exactly who gets access The C++ standard puts it in one sentence: friendship is neither inherited nor transitive. Spelled out: 1. **Not inherited.** A class derived from `CacheInspector` gets no access to `Cache`, even though `CacheInspector` has it. 2. **Not transitive.** If `CacheInspector` declares `friend class Auditor;`, `Auditor` can see `CacheInspector`'s privates, not `Cache`'s. 3. **Not reciprocal.** `Cache` naming `CacheInspector` as a friend gives `Cache` no access to `CacheInspector`'s private members. 4. **Placement does not matter.** The standard says the meaning of a friend declaration is the same whether it appears in the private, protected or public portion of the class. Both of the first two cases fail with the same diagnostic from Apple clang 21: ```plaintext friend2.cpp:3:61: error: 'secret_' is a private member of 'Cache' friend2.cpp:4:89: error: 'secret_' is a private member of 'Cache' ``` ## Access is per class, not per object A frequent interview follow-up is whether a member function can read **another object's** private data. In C++ it can: `bool Cache::sameCapacity(const Cache& other) const` may read `other.capacity_` because access is checked against the class in whose scope the code appears, not against which object is being touched. Copy constructors, member comparison operators and member `swap` functions rely on this every day, and none of them needs `friend`. | Code | Can it name `Cache::capacity_`? | |---|---| | A member function of `Cache`, on any `Cache` object | yes | | A function `Cache` names as a friend | yes | | A member function of a class `Cache` names as a friend | yes | | A class derived from that friend class | no | | A friend of that friend class | no | ## When friend is the right tool Reasonable uses: - **Symmetric operators.** A non-member `operator==` or `operator<<` that needs private data, so that implicit conversions apply to both operands equally. - **Tightly coupled pairs.** A container and its iterator, or a class and its builder, that are designed together and released together. - **Factories** that must call a private constructor. Warning signs: - A friend added only so a **test** can reach internals usually means the behaviour under test is not observable through the public interface. - A long friend list means the class's invariant is maintained by code that does not live in the class. ## Friends and templates Friendship can also name templates, and the forms differ in how much they grant: - `friend class Registry<Cache>;` befriends one specialisation only. - `template <class T> friend class Registry;` befriends every specialisation of `Registry`, including ones written later by other code, which is a much wider grant. - `friend T;` with a template parameter `T` (allowed since C++11) befriends whatever type the template is instantiated with. The wider forms are occasionally necessary, for example when a class template must reach the internals of its other specialisations, but each one enlarges the set of code that can break the class's invariant. ## How to answer Say what is granted (use of private and protected names), by whom (the class itself), to whom (exactly the named function or class), and the three negatives: not inherited, not transitive, not reciprocal. Adding per-class access shows you know when `friend` is unnecessary, and naming a legitimate use, such as a symmetric operator or a container's iterator, shows judgment rather than a memorised rule.

  • In C++, why is operator<< for a class often declared as a friend instead of a member?
    A member `operator<<` would need the class object on the left, as in `cache << std::cout`, because a member operator's left operand is `*this`. Writing `std::cout << cache` therefore requires a non-member taking `std::ostream&` first. If it must print private state, the class declares it a friend; otherwise a non-member using public accessors needs no friendship at all.
  • Does a C++ friend declaration make a member function of the friend class able to call private constructors?
    Yes. Constructors are members and obey the usual access rules, so a private constructor can be called by the class's own members and by its friends. That is the standard way to restrict creation to a factory: make the constructors private and declare the factory class or function a friend.

A friend declaration is like handing a named neighbour a key to your flat: the key does not pass to the neighbour's children or to the neighbour's own friends, and holding your key gives you none to theirs.

  • A class derived from a friend class inherits its friendship.
  • A friend of my friend can also see my private members.
  • Declaring a class as a friend gives me access to its private members too.
  • A friend declaration under private: grants less access than one under public:.
  • A member function can access only its own object's private data, not another object's.