Overloading the Extraction and Insertion Operators


The question arises as how to treat an object of a class with respect to input and output. What could be done would be to break each object into its respective data members and then input or output each of these values. However this is too much work. So how about using the extraction and insertion operators?

Although this would be a better solution, the input and the output of objects can not automatically use the extraction and the insertion operator. The reason is that these operators do not automatically extend to each new data type. While this is true, using operator overloading, C++ has the ability to extend the operators: << and >> to any programmer defined data type

The general form of these two operators is the following:

image from book

 ostream &operator << (ostream &stream, DataType ab) {     // additional code     return stream; } istream &operator >> (istream &stream, DataType &ab) {     // additional code     return stream; } 

image from book

Notice that the output and the first operand use the reference operator. In addition the second operand is the extraction operator is also a reference. These are required in order to move the data in or out as the need requires.

The definitions above are not methods so they would be defined outside of the class' definition. And since they are not methods, the body of these functions can not access private attributes unless they are declared as friends as in the following:

image from book

 friend ostream &operator << (ostream &stream, DataType ab); friend istream &operator >> (istream &stream, DataType &ab); 

image from book

For example: date.cpp shows how this can be done.

The overloading of the insertion and extraction operators in the class Date were not member functions. Since the first argument of these operators must be either istream or ostream objects, they can not be overloaded as member functions. Therefore they were friends, if we wish to preserve encapsulation of OOP. Remember that friend functions are declared in the class' definition and are defined outside of the class definition.

 Note:  If the attributes of the class on which these operators are being overloaded were public, then these overloaded operators would not need to be friend functions.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net