friend
friend grants a function or another class access to a class's private and protected names. Friendship is not inherited, not mutual, and not transitive. It is a targeted hole in encapsulation.
Detailed Explanation
Access specifiers exist so the invariant has one author. Sometimes a function that is not a member still needs to be part of that authoring set. operator<< is the usual example: it must be a non-member so the left operand can be std::ostream, and it often needs to read private fields. friend std::ostream& operator<<(std::ostream&, const User&); makes that legal without making the fields public.
You can friend a free function, a member of another class, or a whole class (friend class Tester;). A friend class's every member can see your privates. That is a wide hole. Prefer friending the specific function.
Friendship is declared inside the class that is giving access. You cannot declare yourself a friend of someone else's class from the outside. The owner of the private data decides.
It is not symmetric: A friending B does not let A touch B's privates. It is not inherited: a function that is a friend of Base is not a friend of Derived. It is not transitive: a friend of your friend cannot see your privates.
A friend function is not a member. There is no this. You pass the object as a parameter. ADL (argument-dependent lookup) still finds a friend declared in the class if the argument's type lives in that namespace. That is why operator<< defined only as a friend inside the class body is found when you write std::cout << user.
Hidden friends are a style: define the friend function inside the class body. It is only found by ADL, which reduces accidental overload matches in other namespaces. Comparison operators in C++20 are often hidden friends.
When not to use friend:
- To let a unit test poke internals. Add a public query, a test-only builder, or a named
debugString()instead. Friend tests couple the test to layout. - To let every class in a module touch every other class. That is a single translation unit with no boundaries, not a design.
- Instead of a public accessor that is part of the real API. If the name is generally useful, make it public.
friend does not grant access to names that are not members. It does not bypass const. A friend still cannot assign to a const member except in a constructor of that class.
A template friend needs a matching template declaration. friend void f<T>(...) versus friend void f(...) are different. Get the forward declaration right or define the friend in-class.
Code Examples
#include <iostream>
#include <ostream>
#include <string>
class User {
public:
explicit User(std::string name) : name_(std::move(name)) {}
friend std::ostream& operator<<(std::ostream& os, const User& u) {
return os << u.name_; // hidden friend: found by ADL
}
private:
std::string name_;
};
int main() {
User u{"ada"};
std::cout << u << '\n'; // prints: ada
}class Key;
class Vault {
friend class Key; // every Key method may read secret_
int secret_ = 42;
};
class Key {
public:
static int peek(const Vault& v) { return v.secret_; }
};
int main() {
Vault v;
return Key::peek(v) == 42 ? 0 : 1;
}Common Gotchas
Friendship does not inherit
`friend void inspect(const Base&);` cannot read `Derived`'s private members, even when the object is a `Derived`.
`friend class Foo;` is a wide grant
every future method of `Foo` can see your privates. Friend the function you need.
A friend is not a member
`friend void User::reset();` if `reset` is a member of `User` looking at another class. Do not write `u.reset()` expecting a free friend.
Defining a friend outside without a matching declaration can make a different function
namespace and template heads must match exactly or you have an overload that is not a friend.