Introducing Friends

As you've seen, C++ controls access to the private portions of a class object. Usually public class methods serve as the only access, but sometimes this restriction is too rigid to fit particular programming problems. In such cases, C++ provides another form of access, the friend. Friends come in three varieties:

  • Friend functions

  • Friend classes

  • Friend member functions

By making a function a friend to a class, you allow the function the same access privileges that a member function of the class has. We'll look into friend functions now, leaving the other two varieties to Chapter 14.

Before seeing how to make friends, let's look into why they might be needed. Often overloading a binary operator (one with two arguments) for a class ...

Get The Waite Group's C++ Primer Plus, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.