1

can someone please explain why the following code compilation fails with message "passing ‘const apple’ as ‘this’ argument of ‘int apple::foo()’ discards qualifiers", and how to resolve it.

#include <cstdlib>
#include <iostream>
#include <string>
#include <map>

using namespace std;

/*
 * 
 */
class apple{
private:
    int a,b,c,d;
public:
    int foo(){
        return a+b+c+d;
    }
};
class ball{
private:
    map<apple,string> mp;
public:
    void foo2(){
        for(map<apple,string>::iterator it = mp.begin();it!=mp.end();++it){
            cout<<it->first.foo()<<endl;
        }
    }

}
int main(int argc, char** argv) {

    return 0;
}
5
  • 3
    int foo {...} -> int foo const {...} Commented Feb 9, 2018 at 21:50
  • 2
    You can't modify the key of a map element in place. Commented Feb 9, 2018 at 21:51
  • This is not your real code due to a missing ; that terminates your class declaration. Here are the errors from the code you posted Commented Feb 9, 2018 at 21:51
  • 2
    The map relies on key values to order itself. It can't let you modify them in place, to maintain its own invariants. Commented Feb 9, 2018 at 21:52
  • StoryTeller's right. You should make it int foo() const so you can call it despite the apple being const - which will work for you because foo() doesn't try to change any of the member data in the apple: it should have been const in the first place. Commented Feb 9, 2018 at 22:27

1 Answer 1

4

Works for me: (added const at the end of foo() and ; on end of ball class). Class apple is a Key in std::map which is declared as const: typedef pair value_type; so accessing key should be also declared as const.

#include <map>
#include <iostream>

using namespace std;

class apple{
 private:
    int a,b,c,d;
public:
    int foo() const {
        return a+b+c+d;
}
};

class ball{
  private:
  map<apple,string> mp;
public:
    void foo2(){
        for(map<apple,string>::iterator it =   mp.begin();it!=mp.end();++it){
         cout<<it->first.foo()<<endl;
    }
}

};

int main(int argc, char** argv) {

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.