mohdyusuf
mohdyusuf

Reputation: 371

Understanding operator overloading 'const' syntax for use in STL map

I am trying to understand the syntax of operator overloading for operator < where the second const word needed for the compiler to be happy.

bool operator < (const point& rhs) const {  // what's the rationale for the second const word here?

Take for example this struct

struct point {
    int x;
    int y;

    point () : x(0), y(0) {}
    point (int _x, int _y) : x(_x), y(_y) {}

    point operator + (const point& rhs) {
        return point(this->x + rhs.x, this->y + rhs.y);
    }
    bool operator < (const point& rhs) const {
        return this->x < rhs.x;
    }
};

This will allow me to use it as key to mymap.

map<point,int> mymap;

Upvotes: 1

Views: 172

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 597016

The outer const on the end of a method declaration tells the compiler that the method's *this object is to be const.

std::map stores its keys as const values. So any operators that are applied to the keys need to be marked as const, or else they will fail to compile. std::map uses operator< by default to order its keys and compare them for equality.

Besides, as good practice, any member method/operator that does not modify the contents of *this should be marked as const anyway. Doing so lets the user know that such operations are meant to be read-only, and lets the compile use them in expressions on const objects.

Upvotes: 2

CiaPan
CiaPan

Reputation: 9570

That second const is a qualifier for the object pointed by the implied argument this. It means the method is not allowed to modify its object. Indeed, comparison needn't - and shouldn't - modify the object being compared.

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31459

The const at the end means that the function will not change the object it is invoked on. This allows the function to be invoked on const objects.

Upvotes: 1

Related Questions