0
istream & /* <--here */ read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

 //main function
 Sales_data total;
    if (read(cin,total))
    {
        Sales_data trans;
        read(cin,trans);
        // ...

I don't quite understand what does the reference mean in this function, I got an error if I delete the reference.

XIAODI
  • 109
  • 5

1 Answers1

1

The reference means that the identity of the object which is returned from the function is the same as the one which will be received by the caller. In other words, it's not a copy, it is the same object. And since the returned object is also one of the function's parameters, which is also taken by reference, the object returned is the same one which was passed in.

The reason you get an error when you remove the reference is because without it, you are trying to return the stream by value, which requires a copy constructor. But std::istream is not copyable, its copy constructor is explicitly deleted.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • thank you, it's very helpful. So can I say "if ...is copyable, than the reference is not required"? – XIAODI Apr 11 '15 at 04:55
  • @XIAODI Semantically speaking, using values by reference (which is more-or-less equivalent to "by pointer") is very different from using them by value. Passing by value invokes a copy constructor and gives you a new object instance. If you have a 1 megabyte object, the reference to that can be very small, but if you return by value then you'll make another 1 megabyte object. Sometimes you need to make a copy, sometimes you don't, sometimes it's not meaningful. [Work your way through a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), it's worth it!! – HostileFork says dont trust SE Apr 11 '15 at 19:01