views:

183

answers:

1

If I wrote an operator == for class Foo (in C++), what happens, exactly? Does it compare each data member against each other?

class Foo
{
   private:
      int bar;

   public:
      bool operator==(const Foo other&)
      {
         return *this == other; //what?
         //is this the same as bar == bar?
      }
}
+14  A: 

The above code will call itself recursively until you get a stack overflow (snicker) and the program crashes. The method itself (the one you wrote) is the equality operator, which is then called again explicitly within the body.

The idea behind overriding the equality operator (operator==) is that you can decide for yourself how equality should be implemented. So you would probably want to make the body of your method do something like:

return this->bar == other.bar;

Which would do what you most likely want.

One of the reasons that you might not want C++ to be "smart" about equality and automatically do a member-wise comparison is that you may have very different ideas about what "equality" means than the C++ standards body.

As an example, you might consider a class with a pointer member to be equal only if the pointers point to the exact same object, or you might only consider them to be equal if the pointed-to-objects are memberwise equal. Or they might be (Note: bad practice here, but people still do it) pointing to some random address as they haven't been initialized yet and dereferencing them will cause a crash ("you" might know this because of some flag variable, but C++ wouldn't when it tried to "helpfully" dereference it).

Adam Batkin
Oh, OK, that makes sense. Thanks for the explanation!
Hooked
+1 for answering a question on stackoverflow.com with "You will get a stack overflow" :-)
Josh