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