Question

When overloading the "==" operator in c++, is there a standard definition as to what equality explicitly means, or a set of guidelines as how "==" should behave?

I currently have a class that does not store its entire self in memory. It basically uses a priority queue to determine how often an object inside itself is being used and when objects are popped from the end of the queue they are removed from memory and written to disk.

So now the problem occurs with equality, what does it mean for two of these objects to be equal. Because we could start with objects A and B which are the same in every way, they have loaded the same data into memory and they have the same data on disk. But then after calling a series of functions on A and B they could now be different. A and B still have the same data on disk but they they have different data loaded into memory. So the question is should A == B resolve to true or false?

Are there a set of rules or guidelines that define how this should work? Or is this just a situation where I decide what makes the most sense for the program and document what "==" does?

Was it helpful?

Solution 2

There's no definition in the standard on how an overloaded operator == should behave.

But a good enough guideline is this - if you have to think about it for as long as you have, you probably shouldn't even be overloading operator ==. If it's not intuitive, it does more harm than good.

So the question is should A == B resolve to true or false?

IMO, it should result in a compiler error. :)

OTHER TIPS

Any operator== overload should respect the axioms of an equivalence relation, that is

  • x == x, for all objects x
  • if x == y, then y == x
  • if x == y and y == z, then x == z.

Many algorithms using == rely on it implementing an equivalence relation, formalized in §17.6.3.1 as the EqualityComparable concept.

ALL operator overloading should do "what you expect". There is no point in having an operator == that returns true if the objects aren't substantially the same. How you define "the same" is of course potentially something we could argue about. One could implement a "nocasestring" where it behaves like a string, but if you have a string "HELLO" and one "hello", they are considered equal, because case doesn't matter. Or if you implemented your own "Float" class, where == does some math to avoid the fragile comparison of regular floating point. So yes, there are cases where == doesn't do EXACTLY "for all elements is a. == b.", but it should really be the exception.

Likewise, if an operator doesn't make totally sense, don't make it do something "surprising" (e.g. - for strings - what does it do? Or multiply one string by another string - multiply by integer may have a meaning).

Surprises in programming is a bad idea. If things don't work the way you EXPECT, you get bad experiences from reading/modifying the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top