Friends

A friend is permitted full access to private and protected members. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

Use the friend specifier to declare a friend in the class granting friendship. Note that friendship is given, not taken. In other words, if class A contains the declaration friend class B;, class B can access the private members of A, but A has no special privileges to access B (unless B declares A as a friend).

By convention, the friend specifier is usually first, although it can appear in any order with other function and type specifiers. The friend declaration can appear anywhere in the class; the access level is not relevant.

You cannot use a storage class specifier in a friend declaration. Instead, you should declare the function before the class definition (with the storage class, but without the friend specifier), then redeclare the function in the class definition (with the friend specifier and without the storage class). The function retains its original linkage. If the friend declaration is the first declaration of a function, the function gets external linkage. (See Chapter 2 for more information about storage classes and linkage.) For example:

class demo;
static void func(demo& d);
class demo {
  friend void func(demo&);
  ...

Friendship is not transitive—that is, the friend of my friend is not my friend (unless I declare so in a separate ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.