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 ?
>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.
-
Your aim is not to change the value of the parameter you take by reference. If that parameter is
constand you take it by aconst&you will therefore still be able to read from it in your function. Had your declaration only saidData& rhs, it would not compile. -
Your aim is not to change the state of
*this(the lefthand side of the==operator). The same applies here. If*thisisconst, theconstqualifier on the member function makes it still possible to use the member function.