ming
ming

Reputation: 239

what does the operator& return type mean?

So from my knowledge,

istream& operator >> (istream &in, int &n);

is the declaration for how >> works (or to overload it in some way)

But I'm confused on this "function's" return type, "istream&".

If I do something like cin >> x; that means I'm putting in the reference to x, but I don't understand the return type istream &, and the parameter "in".

What would this function look like defined? what IS "in"? And what is it actually RETURNING? Because cin >> x does really do anything but take in an input so why does it have to return anything?

Thanks!

Upvotes: 0

Views: 753

Answers (3)

Ted Lyngmo
Ted Lyngmo

Reputation: 118017

It means it's a pass-thru in this particualar case (and many others). It's a contract to return something sensible with the input given. Returning is is the sensible thing since it makes constructs like:

stream >> variableA >> variableB >> variableC

possible. That's because stream >> variableA returns stream an so do the other operations.

Upvotes: 0

Pontus Holmbom
Pontus Holmbom

Reputation: 339

The standard implementation of operator >> would return a reference to the istream &in parameter which means it returns the exact same object.

This is for convenience so you can write code like: cin >> x >> y;

The compiler will take what is on the left side of the operator and put in the first parameter and the right in the second. cin >> x >> y will translate into operator>>( (operator>>(cin, x), y );

This will first add x to the stream and use the return, the stream itself, and write y to that.

Upvotes: 2

3Dave
3Dave

Reputation: 29071

If the function,

istream& operator >> (istream &in, int &n);

returned, instead,

istream operator >>....

Then, things get complicated. In a worst-case scenario, every invocation of >> would copy the stream object and return the copy, which would then be copied and stored in the caller's stack, followed by calls to destructors of all those things that were copied, special circumstances excepted.

By returning a reference, we can do things like chaining:

a << b << "Yo!" << c << "Wassup?" << endl;

...without all of that nonsense.

& means "reference," which is essentially a pointer with stronger compile-time checking and nicer syntax.

Upvotes: 0

Related Questions