Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Type of Overloading >> [duplicate]

Is there any good reason why the standard way of overloading the >> operator for any class returns an object of type istream (or any input stream).

For example, due to this, code like

y = (cin >> x) ;

won't work and it would have if overloading >> had a return type of the input object.

like image 414
user929404 Avatar asked Dec 06 '25 03:12

user929404


1 Answers

For example, due to this, code like

(cin >> x) = y;

won't work. And it would have if overloading >> had a return type of the input object.

No, it wouldn't necessarily - you would in many cases see error: lvalue required as left operand of assignment, unless you return a reference. (click here for a demonstration)

The general reason is that it allows chaining, e.g. doing things like

mystream >> a >> b >> c;

For input/output streams, there is also the added benefit that the stream can be converted to void* (C++03) or bool (C++11), which allows checking for errors in constructs such as

while (cin >> x) { ... }
like image 102
us2012 Avatar answered Dec 08 '25 18:12

us2012