Problem with equality operator.

I just want to share a problem reported in Stackoverflow in which some users are facing compilation issue on overriding the == operator.

Code is like this :


#include <iostream>
#include <conio.h>

class X {
public:
  int a;

  X() { a = 0; }
  bool operator == (const X &b) { return a == b.a; }
  bool operator != (const X &b) { return a != b.a; }
};

class DX : public X {
public:
  int dx;
  DX() { dx = 0; }
  bool operator == (const DX &b) const
  {
    if (dx != b.dx) return false;
    const X *lhs = this;
    const X *rhs = &b;

    if (*lhs != *rhs) return false; // This line is responsible for compilation issue
    return false;
  }

  bool operator != (const DX &b) { return !(*this == b); }
};

void main()
{
  DX d1, d2;
  bool isEqual = d1 == d2;

  std::cout << isEqual;
  _getch();
}


Problem

Problem was that we override the != operator in X class but we don't have an not-equal operator which compare two const X objects. Solution : There are two solution to this problem. 1. Declare the != function is const.i.e. bool operator != (const X &b) { returna != b.a; } 2. In the calling code itself i.e. if (dx != b.dx) return false; X *lhs = this; // Remove const const X *rhs = &b; if (*lhs != *rhs) return false; // No compilation issue now return false;

Thanks

Comments

Popular Posts