Input/Output Operator Overloading in C++

InputOutput Operator Overloading in C++

What is Input/Output operator overloading in C++?

In C++, stream insertion operator “<< ” is used for output and stream extraction operator “>>” is used for input. The stream insertion and stream extraction operators also can be overloaded to perform input and output

Operator overloading is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. In this article we will learn more about input/output operator overloading in C++. You can read more about operator overloading by clicking the button below.

Input/Output Operator Overloading in C++

As we know that cout is an object of ostream class and cin is an object istream class and it is important to make operator overloading function, a friend of the class because it would be called without creating an object i.e. the operators must be overloaded as a global function.

To  call  ‘<<‘ and ‘>>’ operator, we must call it like, ‘cout << obj1’ and ‘cin >> obj1’. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good option most of the time.

Therefore, these operators are overloaded as global functions with two parameters, cout and object of user defined class.

 

C++ program to show Input/Output Operator Overloading

Run
#include <iostream> 
using namespace std;
 
class Length 
{
   private:
      int kmeter;            
      int meter;           
      
   public:
      //default constructor.
      Length() 
      {
         kmeter = 0;
         meter = 0;
      }
      Length(int km, int m)//overloaded constructor. 
      {
         kmeter = km;
         meter = m;
      }
      //overloading '<<' operator.
      friend ostream &operator<<( ostream &output, const Length &l ) 
      { 
         output <<l.kmeter<< "Km "<<l.meter<<"M" ;
         return output;            
      }
      //overloading '>>' operator.
      friend istream &operator>>( istream  &input, Length &l ) 
      { 
         input >> l.kmeter >> l.meter;
         return input;            
      }
};

int main() {
   Length l1(1, 112), l2;

   cout << "Enter the value: " << endl; cin >> l2;
   cout << "First length: " << l1 << endl;
   cout << "Second length: " << l2 << endl;
   

   return 0;
}
Output:
Enter the value: 
2
21
First length : 1Km 112M
Second length :2Km 21M

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription