Skip to Main Content
C++ In a Nutshell
book

C++ In a Nutshell

by Ray Lischner
May 2003
Intermediate to advanced content levelIntermediate to advanced
808 pages
32h 24m
English
O'Reilly Media, Inc.
Content preview from C++ In a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance

C++ High Performance

Viktor Sehr, Björn Andrist
Optimized C++

Optimized C++

Kurt Guntheroth
Mastering C++ Programming

Mastering C++ Programming

Jeganathan Swaminathan

Publisher Resources

ISBN: 059600298XSupplemental ContentErrata Page