UMBC CMSC 202 CSEE | 202 | current 202

Operator <<

One of the most common operators which is overloaded is operator<<.

Money Output

Up to this point, displaying a Money object required the use of the Output( ) function and code that looked like this Money fee(10.25); cout << "The fee is "; fee.Output(); cout << " and is not negotiable\n"; The natural thing to want to do is to use the insertion operator for objects just like for basic data types and write code like this Money fee(10.25); cout << "The fee is " << fee << " and is not negotiable\n"; By overloading operator<<, we can do just that and assure that Money objects are always displayed in the same format.

The statement cout << fee; is actually a function call.
The name of the function being called is operator<<. The compiler looks for a function whose signature is

ostream& operator<< (ostream& out, const Money& money); Assuming such a function exists, the compiler generates the function call. What if the function doesn't exist?

The operator<< function

In this example, the code for Money's operator<< is written as a friend function. The declaration for the overloaded operator<< as friend function inside the Money class definition would be friend ostream& operator<< (ostream& out, const Money& amount);

Of course, if sufficient accessors exist, operator<< need not be a friend. The implementation of the function is shown below along with its pre- and post-conditions.

// PreConditions: none // PostConditions: // the Money argument is displayed as dollars // and cents with a leading $ // the modified output stream is returned ostream& operator<< (ostream& out, const Money& money) { out << "$" << money.m_dollars << "." << money.m_cents; return out; } Why does this function return an ostream reference?


  1. You can and should overload operator<< for all your objects.
  2. Note that we did not output an endl.
  3. operator<< is a binary operator. The left hand operand is an ostream object. Therefore, operator<< cannot be a member function of your class.
  4. operator<< is not a member function.
  5. operator<< always returns an ostream&.
  6. You can also overload the extraction operator, operator>>, for inputting a class.

Last Modified: Monday, 28-Aug-2006 10:15:53 EDT