PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

Right way to overload < operator?

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.

Upvotes: 0

Views: 123

Answers (4)

dillon
dillon

Reputation: 29

It seems better to me to hide the 'lname' field as private.

return lname.compare(other.getName()) < 0;

Upvotes: 2

aschepler
aschepler

Reputation: 72473

As others have pointed out, your operator< doesn't allow the left side to be const. Changing the function signature to

bool User::operator<(const User& other) const

is an improvement. But I would actually recommend making it a non-member function instead:

class User {
public:
    friend bool operator<(const User& u1, const User& u2);
    // ...
};

bool operator<(const User& u1, const User& u2)
{
    // ...
}

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 < b attempts implicit conversions on both a and b to see if your operator< is a viable overload. But with a member function, implicit conversions can apply to b, but not to a: a must be of type User or a derived type. This can lead to surprising situations where a < b compiles but b < a doesn't.

Upvotes: 3

paddy
paddy

Reputation: 63481

The correct way to implement operator< is as a const-function:

bool User::operator<( const User& other ) const

This means that the function does not modify its members and thus can be called on const instances of your class.

Upvotes: 1

Mankarse
Mankarse

Reputation: 40643

Try:

bool User::operator<(const User& other) const
{
    return lname.compare(other.lname) < 0;
}

Upvotes: 1

Related Questions