Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why should the equality operator be declared with const qualifiers?

I was watching a seminar on c++ best practices, and the guy 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 is missing in this code ? As a newbie i thought nothing is 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 i know this is like a promise not to modify the object (correct me if I’m wrong please). But can someone explain why is this mandatory ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading