The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Operator Overloading and <<

There are two operators that are common to many object types: << and =. << converts the object to some reasonable string representation so it can be outputted, and = is used to copy objects.

When you output an object using cout, C++ checks to see whether you have provided a << definition for that object. If it can't find one, it will refuse to compile and give an error such as

  complex.cpp:11: no match for `_IO_ostream_withassign & << Complex &'

Here is what << might look like for the Complex class:

  ostream& operator << (ostream& os, Complex& num) {
    os << num.real << " + " << num.imag << "i";
    return os;

Whenever you pass an object to an output stream such as cout, C++ invokes the << operator on that object and outputs the result. In this case, the output is 1 + 2i.

The return type for << is ostream&, which is the datatype of a cout object. By returning the os object (which, like ostream, is just an abbreviation of output stream), you can string together multiple << commands such as

  cout << "Your two numbers are " << num1 << " and " << num2;

To illustrate why that's a good thing, consider what you would be forced to do if you didn't return the ostream object:

  cout << "Your two numbers are ";
  cout << num1;
  cout << " and ";
  cout << num2;

Because the first example allows stringing << statements together, all the display code fits easily on one line. The output from both statements is the same, displaying "Your two numbers are 3 + 2i and 1 + 5i".

This version of << does not look good if the imaginary part is negative. As an exercise, fix it.

Last Update: 2005-12-05