Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return type in stream operator overloading

The purpose of program is to take input, assign those values to the members of the class and display the output, with the input and output operation being done by overloading stream operators.

#include <iostream>
using namespace std;
class MyClass {
int x, y;
public:
  MyClass(int i, int j) { 
     x = i; 
     y = j; 
  }

  friend ostream& operator<<(ostream &stream, MyClass ob);
  friend istream& operator>>(istream &stream, MyClass &ob);
 // friend void operator<<(ostream &stream, MyClass ob);
 // friend void operator>>(istream &stream, MyClass &ob);
};

ostream& operator<<(ostream &stream, MyClass ob)
{
  stream << ob.x << ' ' << ob.y << '\n';

  return stream;
}

istream& operator>>(istream &stream, MyClass &ob)
{
  stream >> ob.x >> ob.y;

   return stream;
}

int main()
{
MyClass abt(30,23);
cin>>abt;
cout<<abt;
return 0;
}

In the example, if data is taken from input stream 'cin' and the values are assigned inside the function, why should 'istream' be returned back. I have seen all tutorials return stream in operator overloading function. What is the purpose of return value?

like image 246
user3124361 Avatar asked Dec 25 '22 22:12

user3124361


2 Answers

In the example, if data is taken from input stream cin and the values are assigned inside the function, why should istream be returned back?

This is done to allow "chaining".

The operator takes its two parameters from both sides of >>. The stream comes from the left, and the variable comes from the right. When you do this

cin >> x >> y;

the first expression cin >> x is on the left of the second expression, which means that the result of cin >> x becomes ... >> y's input stream. That is why the operator needs to return the same input stream that has been passed into it.

like image 59
Sergey Kalinichenko Avatar answered Dec 27 '22 11:12

Sergey Kalinichenko


How do you suppose the following works?

stream >> ob.x >> ob.y;

That's exactly the same as:

(stream >> ob.x) >> ob.y;

So what's the value of stream >> ob.x?

like image 41
rici Avatar answered Dec 27 '22 11:12

rici