Search code examples
c++function-qualifier

const member function


I have following piece of code:

class Test{
private:
    int id;
public:
     Test(int v):id(v) {}
     int getId() { return id;};          // however,I change this method signature
                                            int getId() const { return id;};
                                            and all the errors gone
};

 struct compare{
   bool operator()(const Test& t1, const Test& t2){
    return t1.getId() < t2.getId();      // got error here
   }  
 };

 int main(int argc, char *argv[]){
   set<Test, compare> s;
   Test str[] = {Test(1), Test(2), Test(3)};
   for (int i = 0; i < 3; ++i){
     s.insert(str[i]);
   }
   for (set<Test>::iterator it = s.begin(); it != s.end(); ++it){
     cout << it->getId() << "\n";        // got error here
   }    
   return EXIT_SUCCESS;
 }

I got this error when I called the method getId() with that code:

passing `const Test' as `this' argument of `int Test::getId()' discards qualifiers

I don't know why I need const in the method getId() to fix that error ? Thanks


Solution

  • bool operator()(const Test& t1, const Test& t2)
    

    Your operator takes references to const Test objects. You can only call const-qualified member functions via a reference to a const-qualified type.

    set<Test>::iterator it = s.begin()
    

    The elements of a std::set are immutable: you cannot change them. Because of this, iterators into a std::set are always to a const-qualified type of object.