Why am I receiving an error when I do not put const in the function bool operator<(const Node& otherNode) //const?
stl_algo.h:91: error: passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers
Should all the overloaded operators be constant?
class Node {
public:
double coordinate;
bool operator==(const Node& other) const{
return coordinate == other.coordinate;
}
bool operator<(const Node& other) const{
return coordinate < other.coordinate;
}
};
Not all operators, but
==and<should definitely be madeconst, yes. They logically don’t modify either of the objects being compared.The error likely comes from calling a non-
constmethod from aconstone, e.g.:In this case, since the method
isSmallerisconst,thisis implicitly aconstobject, thereforeoperator <also has to beconstin order for the call within that context to be valid.From the error message, it appears that
Node::operator <is being called on aconstobject, from a function instl_algo.h– sorting/ordering functions, hashing functions, etc.