Overloading of stream insertion “<<" and stream extraction ">>” operator in C++

In this chapter we shall see how to overload stream insertion and stream extraction operator.
Stream Insertion “<<” operator is used for output.
Stream Extraction “>>” operator is used for input.
cout is an object of Ostream Class.
cin is an object of Istream Class.

Few important points on stream insertion and extraction operator

We need to make the overloaded operators friend of the class that we are overloading.
This is because we should be able to call the operator without creating the class object.
And also we need to make the overloading function as global.
Below is the syntax of overloaded extraction operator:
istream& operator >> (istream &in, MyClass &c);
As you can see, we are returning a reference of the istream object.
Similarly, for insertion operator “<<“, we return a reference of ostream object.

What is the reason for that?

There are several reasons, few of them are as below:
1. It can be used to chain the input and output operations.
Example:
cin >> a >> b;
cout<<a << b;
2. As you have taken the reference of istream, ostream, you cannot return the object, but only the reference recieved can be returned.
Example:
#include <iostream>
// for more tutorials check www.prodevelopertutorial.com
using namespace std;
class MyClass
{
    private:
        int num_1;
        int num_2;
        
    public:
        MyClass(int a = 0, int b =0)
        {  
            num_1 = a;   
            num_2 = b; 
        }
        friend ostream & operator << (ostream &out, const MyClass &c);
        friend istream & operator >> (istream &in,  MyClass &c);
};
 
ostream & operator << (ostream &out, const MyClass &c)
{
    out << "num_1 = "<<c.num_1<< " num_2 = "<< c.num_2 << endl;
    return out;
}
 
istream & operator >> (istream &in,  MyClass &c)
{
    cout << "Enter num_1"<<endl;
    in >> c.num_1;
    cout << "Enter num_2"<<endl;
    in >> c.num_2;
    return in;
}
 
int main()
{
   MyClass obj;
   cin >> obj;
   cout << "The values are";
   cout << obj;
   return 0;
}

Output:

Enter num_1
Enter num_2
The values arenum_1 = 1 num_2 = 2
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *