Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of Equality

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?

like image 257
David Saxon Avatar asked Dec 20 '12 22:12

David Saxon


People also ask

What is the best definition for equality?

What is equality? Equality is about ensuring that every individual has an equal opportunity to make the most of their lives and talents. It is also the belief that no one should have poorer life chances because of the way they were born, where they come from, what they believe, or whether they have a disability.

What is the Oxford definition of equality?

/iˈkwɑːləti/ [uncountable] ​the fact of being equal in rights, status, advantages, etc.


2 Answers

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.

like image 187
Fred Foo Avatar answered Sep 27 '22 20:09

Fred Foo


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. :)

like image 44
Luchian Grigore Avatar answered Sep 27 '22 19:09

Luchian Grigore