AdamSpurgin
AdamSpurgin

Reputation: 961

Having trouble when overloading the '<' operator for a map

I am trying to overload the '<' operator so that i can use the std::map in a project. The prototype in the class definition looks like this: bool operator<(const Vertex&);, and the body of the function looks like this:

bool Vertex::operator <(const Vertex& other){
    //incomplete, just a placeholder for now
    if(px != other.px){
        return px < other.px;
    }
    return false;
}

and the error i'm getting is this: /usr/include/c++/4.7/bits/stl_function.h:237:22: error: passing ‘const Vertex’ as ‘this’ argument of ‘const bool Vertex::operator<(Vertex)’ discards qualifiers [-fpermissive]

Upvotes: 0

Views: 99

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Since your operator< overload doesn't modify the object pointed to by this, you should mark it as a const member function. That is, for the declaration, add a const to the end:

class Vertex {
  // ...
  bool operator<(const Vertex& other) const;
  // ...
};

Upvotes: 1

paddy
paddy

Reputation: 63451

Your function needs a const qualifier:

bool Vertex::operator <(const Vertex& other) const {
    //...
}

That means it can be called on const objects.

Upvotes: 1

Related Questions