Home > Enterprise >  Is declaring const keywords required with the equality operator?
Is declaring const keywords required with the equality operator?

Time:01-12

I was watching this seminar on C best practices, and the speaker gave this code example:

struct Data{
  int x;
  int y;

  bool operator==(Data &rhs){
   return x == rhs.x && y == rhs.y;
}
};

He then asked what was missing in this code. As a newbie I thought that nothing was missing, but then he pointed out that 2 const keywords were missing, like so:

struct Data{
  int x;
  int y;

    bool operator==(const Data &rhs) const{
     return x == rhs.x && y == rhs.y;
  }
};

Now I think this is like a promise not to modify the object. But can someone explain why these const keywords are necessary?

CodePudding user response:

If you did not have const on both places in your operator==, this would not compile:

void foo(const Data& lhs, const Data& rhs) {
    if(lhs == rhs) { // requires `operator==(const Data &rhs) const`
       // do stuff
    }
}

why is this mandatory

It is not - but it's good practice - and failing to implement it that way will severely inhibit the ability to interact with the standard (and other) libraries.

  1. Your aim is not to change the value of the parameter you take by reference. If that parameter is const and you take it by a const& you will therefore still be able to read from it in your function. Had your declaration only said Data& rhs, it would not compile.

  2. Your aim is not to change the state of *this (the lefthand side of the == operator). The same applies here. If *this is const, the const qualifier on the member function makes it still possible to use the member function.

  • Related