operator<< overloading

I don't get the 'chaining' part of this overload. Could someone explain it to me please ?
I've overloaded for this call: cout <<obj1<<obj2<<obj3; but it seems to only work on obj1.

Thanks

Your function should look something like:
1
2
3
4
5
std::ostream& operator<<(std::ostream& os, const Obj& obj)
{
    // do obj stuff
    return os;
}
The bold parts are the things that enable chaning. It works like this.

Using your example, this is equivalent to what gets called.
1
2
3
std::ostream& tmp1 = operator<<(std::cout, obj1);
std::ostream& tmp2 = operator<<(tmp1, obj2);
std::ostream& tmp3 = operator<<(tmp2, obj3);
I hope you can now see why the return value is so crucial to the whole thing working.
Topic archived. No new replies allowed.