What's unclear to me here is what it actually is for a function to return a reference variable, and Prata (p. 520) emphasizes that you need to do that if you want your overloaded << to work properly.
He uses the example of an object of the class Time, which has as member variables integers for hours and minutes. So, the definition of the overloaded << looks like this:
Code:
ostream & operator<<(ostream & os, const Time &t)
{
os << t.hours << " hours, " << t.minutes << " minutes";
return os;
}
It's clear to me why the function needs to return an ostream object, namely to get a line like cout << trip << " on Tuesday.\n"; to work properly (where trip is a variable holding a Time object).
But why wouldn't it work to make the definition read simply:
Code:
ostream operator<<(ostream & os, const Time & t)
{
...
}
That's where my understanding is breaking down. It seems to me that the latter definition should also return cout, just not cout as reference object.
I guess one reason for the necessity of the & might be that there can only be ONE cout object (just as Jet Li wanted to achieve!) and that without the & the compiler would try unsuccessfully to create another. So, when we try to get outside the function and go beyond the return os; line, without the &, the compiler tries to make a copy of cout to use as value outside the function. But it can't do it since there can only be 1 cout. Hence, maybe not even compiler error when you don't use the & but definitely run-time error when you try to make use of the function without the & (?).
Am I on the right track in attempting to understand this?
P.S.: I guess this question has a lot to do with understanding what cout actually is. I'm guessing that it's essentially a built-in variable representing the content of THE location in memory which the OS defines as holding screen contents for the current location. That understanding could no doubt also use a good deal of elaboration for the whole dynamic process but is at least the way I kind of picture the basics of it.