previous | start | next

## Overloading Operators

- For many classes, you want to print the object with the familiar `<<` notation.
- The output operator takes a parameter of type `ostream&` (because printing modifies the stream) and the object to be printed.

  >     ostream& operator<<(ostream& out, Time a)
  >     {
  >        out << a.get_hours() << ":";
  >        if (a.get_minutes() < 10) out << "0";
  >        out << a.get_minutes() << ":";
  >        if (a.get_seconds() < 10) out << "0";
  >        out << a.get_seconds();
  >        return out;
  >     }

- The `<<` operator returns the out stream to enable chaining of the `<<` operator.

  >     cout << now << "\n";

  really means

  >     (cout << not) << "\n";

  that is

  >     operator(cout, now) << "\n";

- The call to `operator(cout, now)` returns `cout`, then `cout << "\n"` prints a new line.

previous | start | next