One of the first things you do when you are designing and implementing a class is to determine some way to get the data into your class objects and some way to get data out of your objects. Sometimes member functions work well for this, but at other times you want to use the input and output operators like you use with the built-in data types.

In this article I’m going to show you how to overload the input operator (>>) and the output operator (<<) so that you can use them with your class objects.

A Few Words about Operator Overloading

C++ is one of the few languages to allow operator overloading. Overloading operators is useful with classes because there are times when you want to use a class object with an operator that does not recognize that object. This will be true for all your user-defined types (classes).

For an example, consider a class called IntData. This class is a wrapper class for integers that includes (hypothetically) some functionality not found in the int type itself. If I want to add two IntData objects together, without operator overloading I will have to provide a member function for doing this. Here is an example code fragment:

IntData d1(1);
IntData d2(2);
IntData d3 = d1.add(d2);

What I would rather do is this:

IntData d1(1);
IntData s2(2);
IntData d3 = d1 + d2;

I cannot do this without operator overloading because the + operator is not defined to work with my IntData objects. With operator overloading, on the other hand, I can have the + operator recognize my IntData objects and perform the resulting addition. This makes operator overloading an important part of many class definitions.

This also applies to operations such as input and output. I can’t simply write this to display the contents of an IntData object:

cout << d1 << endl;

The << operator has no knowledge of my class definition. Nor can I use the input operator to put data into an IntData object:

cin >> d2;

To allow these operations to work so that the users of my class can use these objects in the same manner they use primitive data types, I need to overload the input and output operators to recognize IntData objects.

#cpp #learn-to-code #object-oriented #operator-overloading #learn-to-program #c++

Learning C++: Overloading the Input and Output Operators
1.35 GEEK