Overloading the '<<' Insertion Operator

The operator << is the most commonly overloaded operator, and ironically, the most complex. Just as we use cout to display values of basic data types, we will overload << such that it displays our complex objects. The strange thing about the << operator is that is always operates on a heterogeneous pair of operands: the LHS is "cout" or some other ostream, and the RHS is the class you are trying to output. When an operator function is overloaded as a member function, the LHS is the implicit calling object; here, that would be "cout", which is not a class we can add a member function to. So, the operator << is not overloaded as a member function. Hence it is not a part of our Complex class. However, we do define it in Complex.h and implement in Complex.cpp.

The operator << is a binary operator: the left-hand operand is the ostream object cout and the right-hand operand is our Complex object. The prototype of the operator function for overloading << is:

ostream& operator<< (ostream& out, const Complex& number);

The operator<< can also be implemented as a friend function. Since we have accessors for our Complex class ( GetReal() and GetImaginary() ), there is no need for making it a friend function in this case.

The operator<< function is implemented in the following manner: