|
-
February 21st, 2008, 08:54 AM
#1
operator<< overloading
Hi forum 
Take this example code:
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)
Code:
A.operator<<(B);
Object Temp("test");
A.operator<<(Temp);
A.operator<<(C);
OR
B)
Code:
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:
Code:
if( (A << B << C) == D) return;
Am I right or am I mistaken?
Any help is highly appreciated
-
February 21st, 2008, 09:02 AM
#2
Re: operator<< overloading
It is equivalent to:
Code:
A.operator<<(B).operator<<("test").operator<<(C);
Or in other words:
Code:
Object& ref1 = A.operator<<(B);
Object& ref2 = ref1.operator<<("test");
Object& ref3 = ref2.operator<<(C);
-
February 21st, 2008, 09:04 AM
#3
Re: operator<< overloading
Neiter A nor B, but
Code:
((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.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
-
February 21st, 2008, 09:09 AM
#4
Re: operator<< overloading
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.
-
February 21st, 2008, 01:16 PM
#5
Re: operator<< overloading
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.
-
February 21st, 2008, 01:20 PM
#6
Re: operator<< overloading
Good that you understood..But I thing I still dont understand is why you have overloaded operator<< in the first place that way.
Dont forget to rate my post if you find it useful.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|