English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Input/Output Operator Overloading

C++ Operator Overloading and Overloaded Functions

C++ You can use stream extraction operator >> and stream insertion operator << to input and output built-in data types. You can overload stream extraction operator and stream insertion operator to operate on objects and other user-defined data types.

It is important here that we declare the operator overloading function as a friend function of the class, so that we can call the function directly without creating an object.

The following example demonstrates how to overload the extraction operator >> and insertion operator <<.

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 to infinity
      int inches;           // 0 to 12
   public:
      // Required constructor
      Distance()
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      friend ostream &operator<<(ostream &output, 
                                       const Distance &D
      { 
         output << "F: " << D.feet << " I: " << D.inches;
         return output;            
      }
 
      friend istream &operator>>(istream &input, Distance &D)
      { 
         input >> D.feet >> D.inches;
         return input;            
      }
};
int main()
{
   Distance D1(11, 10), D2(5, 11), D3;
 
   cout << "Input object value: " << endl;
   cin >> D3;
   cout << "First Distance : " << D1 << endl;
   cout << "Second Distance :" << D2 << endl;
   cout << "Third Distance :" << D3 << endl;
 
 
   return 0;
}

When the above code is compiled and executed, it will produce the following results:

$./a.out
Input Object Value :
70
10
First Distance : F : 11 I : 10
Second Distance : F : 5 I : 11
Third Distance : F : 70 I : 10

C++ Operator Overloading and Overloaded Functions