reference to ostream object

Hey there.

I'm told, in overloading functions topic, if, for example, I had a class called "Number" and an object in that class called "ten", and intended to print out the value using the following syntax,
 
std::cout << ten;


I should define a friend function and implement it as follows:
1
2
3
4
5
6
7
using namespace std;

ostream & operator<< (ostream & os, Number & num)
{
os << num.value;
return os;
}


I'm just curious, why should the function return type would be a refernce? Why should I pass a reference to an ostream object as the argument? Why the otherwise won't work?

Thanks in advance.
C++ streams are not copyable (for good reason), so you have to pass them around by reference. The reason you return the reference is because the << and >> operators need to be able to be chained.
Topic archived. No new replies allowed.