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?
In the example, if data is taken from input stream
cin
and the values are assigned inside the function, why shouldistream
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.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With