I understand that this
double grade(int &hw) {}
is passing an argument by reference. And that this
double a;
double &b = a;
is making b a reference to a.
But what about this
istream &read_hw(istream &in) {}
What does the reference operator before the name of the function signify, and in what cases would the effect be desired?
This is the type of the return value. In that case, a
istream &is returned, so a reference to an istream object.This is desired if the returned value is meant to be modified by the caller. E.g. you can return a reference to an member variable to make it modifyable
In such a case, the member
i()can be used as getter and setter:In the your case of iostreams, the method returns a reference to the passed-in istream object, to enable chaining, e.g. like
cout << a << b << c, which calls 3 timesostream &operator << (ostream &, <whatever>)