I have a class called user which has a lname field. Is this the right way to overload the “<” operator?
bool User::operator<(const User& other)
{
std::cout << "< operator was called" << std::endl;
if (this != &other)
{
if (lname.compare(other.lname) == 0)
{
return true;
}
}
return false;
}
I am trying to use this in a more complicated set of things and it is failing – just want to make sure this much is right.
As others have pointed out, your
operator<doesn’t allow the left side to beconst. Changing the function signature tois an improvement. But I would actually recommend making it a non-member function instead:
For one thing, it’s a little more legible in my opinion.
But also, it sometimes makes a technical difference. With a non-member function, the expression
a < battempts implicit conversions on bothaandbto see if youroperator<is a viable overload. But with a member function, implicit conversions can apply tob, but not toa:amust be of typeUseror a derived type. This can lead to surprising situations wherea < bcompiles butb < adoesn’t.