Comparison operator overloading

Hi there, I have a question on one of my C++ homework assignments that has me vexed.

"Why might it be hazardous to overload comparison operators?"

My thoughts are two-fold on the answer:

first, because one class may contain a multitude of different dimensions & units, comparison of an entire class to another might be too ambiguous as to precisely what members are being compared.

Second, and I'm not sure that this is true, but wouldn't overloading the < operator, for example, make ordinary comparisons of object members impossible?

Any other thoughts on the matter?


Thanks for any help anyone can provide.
"Why might it be hazardous to overload comparison operators?"
I can't think of anything that could be called "hazardous". There are possible semantic ambiguities, as you've said, but if you're comparing two objects, the semantics should follow the Principle of Least Astonishment. For example, if you have two strings, comparing them shouldn't be the same as comparing their sizes. If it's not possible to define a single sensible comparison function then perhaps the types are not comparable.

Second, and I'm not sure that this is true, but wouldn't overloading the < operator, for example, make ordinary comparisons of object members impossible?
No.
Last edited on
The only answer I can think of is that it might be misinterpreted by another user like you said but this is what those double backslash things are for so I don't see it as being a real world problem.

It's not the number of attributes that would be a concern, if you were for example comparing two basic shapes then you would have enough like attributes to determine if one was greater then the other, but you won't ever need to see if a rectangle is greater then the color green. Maybe if the individual attributes each held a different weight it might be a problem but I have a feeling that this is stepping outside the scope of a begginner class.
double backslash


http://xkcd.com/727/
Topic archived. No new replies allowed.