I'm learning about operator overloading in C++, and I see that ==
and !=
are simply some special functions which can be customized for user-defined types. My concern is, though, why are there two separate definitions needed? I thought that if a == b
is true, then a != b
is automatically false, and vice versa, and there is no other possibility, because, by definition, a != b
is !(a == b)
. And I couldn't imagine any situation in which this wasn't true. But perhaps my imagination is limited or I am ignorant of something?
I know that I can define one in terms of the other, but this is not what I'm asking about. I'm also not asking about the distinction between comparing objects by value or by identity. Or whether two objects could be equal and non-equal at the same time (this is definitely not an option! these things are mutually exclusive). What I'm asking about is this:
Is there any situation possible in which asking questions about two objects being equal does make sense, but asking about them not being equal doesn't make sense? (either from the user's perspective, or the implementer's perspective)
If there is no such possibility, then why on Earth does C++ have these two operators being defined as two distinct functions?
'undefined' != expression
is always true (or false, or undefined), regardless of whether expression can be evaluated. In this casea!=b
would return the correct result as per definition, but!(a==b)
would fail ifb
cannot be evaluated. (Or take a lot of time if evaluatingb
is expensive). – Dennis Jaheruddin(NaN != NaN) == true
– chiliNUT