Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ostream << operator overloading and it's return type

I learnt how to do operator overloading of Stream Insertion Operator. But one doubt remains.

#include<iostream>

class INT
{
    int i;
    friend std::ostream& operator<<(std::ostream&,INT&);
public:
    INT():i(100){}
};

std::ostream& operator<<(std::ostream& obj,INT & data)
{
   obj<<data.i;
   return obj;
}

int main()
{
    INT obj;
    std::cout<<obj;
}

What significance return obj; has?

Do that return have any use further?

Are We forced to do that return because of the syntax of the operator<< without any usefulness?

like image 604
InQusitive Avatar asked Dec 10 '25 07:12

InQusitive


1 Answers

Remember how you can write code like this:

cout << "The data is: " << somedata << endl;

This is actually the same as:

((cout << "The data is: ") << somedata) << endl;

For this to work, the << operator has to return the stream.

like image 84
Joni Avatar answered Dec 11 '25 20:12

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!