Click to See Complete Forum and Search --> : operator<< overloading


AvalonX
February 21st, 2008, 07:54 AM
Hi forum :)

Take this example code:



class Object
{
public:

Object(const char *String);

Object &operator<<(const Object &LHS);
}

Object A, B, C, D;

A << B << "test" << C;



What would the last statement be equivalent to?

A)



A.operator<<(B);
Object Temp("test");
A.operator<<(Temp);
A.operator<<(C);



OR

B)


Object Temp("test");
A.operator<<( B.operator<<( Temp.Operator<<( C ) ) );


I believe it is A, but why then do so many tutorials on operator<<-overloading say something like:

"We have to return the [in this case class Object] object, since this allows us to chain multiple objects to be output on a single line (e.g.: A << "blah" << B << C; )."

If the correct equivalent is A, this is wrong, because you don't NEED to return the object for that. You would only have to return it for things like:


if( (A << B << C) == D) return;


Am I right or am I mistaken?

Any help is highly appreciated :)

Zaccheus
February 21st, 2008, 08:02 AM
It is equivalent to:
A.operator<<(B).operator<<("test").operator<<(C);
:)

Or in other words:


Object& ref1 = A.operator<<(B);
Object& ref2 = ref1.operator<<("test");
Object& ref3 = ref2.operator<<(C);

treuss
February 21st, 2008, 08:04 AM
Neiter A nor B, but
((A.operator<<(B)).operator<<(Object("test"))).Operator<<(C);So it will run A << B, store the result in a temp and then run temp << Object("test"), and so on.

laserlight
February 21st, 2008, 08:09 AM
If the correct equivalent is A, this is wrong, because you don't NEED to return the object for that.
You should test your hypothesis with an example program where operator<< returns void and yet you attempt operator chaining. After that contrapositive logic will show you that the correct equivalent is not A, as Zaccheus and treuss have noted.

AvalonX
February 21st, 2008, 12:16 PM
Thank you so much to all of you for your responses. You helped me a lot and I understand now why I was mistaken...

:)

Take care.

code_carnage
February 21st, 2008, 12:20 PM
Good that you understood..But I thing I still dont understand is why you have overloaded operator<< in the first place that way.