Overloading the Stream Insertion (<<) Operator

The stream insertion operator function (Fig. 10.4, lines 11–16) takes an ostream reference (output) and a const PhoneNumber reference (number) as arguments and returns an ostream reference. Function operator<< displays objects of type PhoneNumber. When the compiler sees the expression

cout << phone

in line 22 of Fig. 10.5, the compiler generates the non-member function call

operator<<( cout, phone );

Function operator<< displays the parts of the telephone number as strings, because they’re stored as string objects.

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

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