0

In Koenig and Moo's Accelerated C++ book on page 57, they provide the function shown below, which returns in. The stated reason for doing so is to indicate whether the attempted input was successful (page 55). However, in was passed by reference as one of the arguments to the function. So can't you just get the state of the istream by looking at the original object?

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        // get rid of previous contents
        hw.clear();

        // read homework grades
        double x;
        while (in >> x)
            hw.push_back(x);

        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}
dpritch
  • 1,149
  • 13
  • 15
  • 1
    You could, but `while (read_hw(s, data)) { ... }` is much nicer than `while (s) { read_hw(s, data); if (s) {...}}` – molbdnilo Jun 09 '17 at 21:08

2 Answers2

8

It allows you to compose fluent interfaces, like this

read_hw(cin, hw).read_something_else(cin, x).blah_blah(cin, y)

since each method call returns a reference to the istream object, it can be used to chain method calls.

That is in fact what happens when you do

cin >> a >> b;

Each operator>> function call returns a reference to the stream, so it can be chained.

It can also allow you to loop and read in from an istream object the idiomatic way in C++, for example

while (read_hw(cin, hw)) { 
    do_something_with_hw(hw);
}
Curious
  • 20,870
  • 8
  • 61
  • 146
1

BLUF: Yes.

Longer version: By returning the in it signals to the implementor that what they passed in is also an out parameter. It's a convention. If your functions only communicate out by return values, then you can distinguish from your inputs in the formal parameter lists.

You don't need to do this, but it's helpful if you typically only ever return a single value. Then you don't have to consult the documentation for each call. By convention you know that "the thing I get back indicates status."

My 2c, this practices maps poorly to lots of real-world coding examples and without the consistency, it isn't compelling or useful. I generally don't use it. As a related example, Go and Lua code both allow for returning multiple values. With languages as those it is more natural to be able to have the first returned value be the result of a successful execution of the function and the second value be the "status" of the result. OK, Bad, etc.

Sam
  • 2,939
  • 19
  • 17