I am attempting to teach myself C++ by reading through a textbook and doing practice problems and stuff, and the topic I am currently learning is a little confusing to me and I am hoping to get some clarification. I have looked online for a clear answer to my question, but have not yet found anything.
I am currently learning the details of IO Classes in the standard library, and the section I am on right now gives some examples that has functions that pass and return IO objects.
For example:
istream &get_value(istream &input)
{
int value;
input >> value;
return input;
}
int main()
{
get_value(cin);
return 0;
}
I understand on a high-level view what is happening here. The get_value
function has a reference to an input object type and it also takes in a reference to an input object, which in my example I used to commonly used cin
object. I get that this function is reading input from the user in the console and is storing that input as value
.
What I do not understand is what the reason for returning the input object is. Why shouldn't this function have a type void
? What could the input object I am using be used for? I know I am not using it for anything right now, but what could it be used for?
The return value is so you can "chain" the calls between the stream operators <<
and >>
. Operator overloading is a good motivation for this "chaining".
using namespace std;
class book {
string title;
string author;
public:
book(string t, string a) : title(t), author(a) { }
friend ostream &operator<<(ostream &os, const book &x);
}
ostream &operator<<(ostream &os, const book &x)
{
os << x.title << " by " << x.author << "\n";
return os;
}
int main()
{
book b1 { "Around the World in 80 Days", "Jules Verne" };
book b2 { "The C Programming Language", "Dennis Ritchie" };
cout << b1 << b2; // chaining of operator<<
}
If operator<< didn't return an ostream, we would not be able to pass the modified ostream from the first operator<< to the second one. Instead we would have to write
cout << b1;
cout << b2;
The same applies for input operations, like in your case, with >>