Operator Overloading  «Prev  Next»
Lesson 11Overloading I/O operators
Objective Reference to stream needed when overloading I/O operators.

Overloading I/O Operators

Explain why using a reference to a stream is needed when overloading the input/output operators.
In keeping with the spirit of OOP, it is important to overload << and >> to output and input user-defined types as well as native types. The operators << and >> have two arguments:
  1. an ostream& or an istream& respectively
  2. the ADT

and the operators must produce an ostream& or an istream& respectively.
Whenever overloading << or >>, you want to use a reference to a stream and return a reference to a stream because you do not want to copy a stream object.

Overloading operator << is similar to overloading operator+ since they are both binary operators, except that the parameter types are different.
Consider the expression cout << cPoint.
Question: If the operator is <<, what are the operands?
Answer: The left operand is the cout object, and the right operand is your Point class object.
cout is actually an object of type ostream. Therefore, the overloaded function will look like this:

friend ostream& operator<< (ostream &out, Point &cPoint);

Implementation of operator<< is fairly straightforward, because C++ already knows how to output doubles using operator<<, and our members are all doubles, we can simply use operator<< to output the member variables of our Point. Here is the above Point class with the overloaded operator<<.