const at the end of one method giving error
Question
I don't understand why I get error with che const at the end of my method. The method print doesn't change any class member, right?
class Hello{
public:
int get_member() {return member_;};
void print() const {
cout<<get_member()<<endl;
};
private:
int member_;
};
The error message is: error passing "const Hello" as "this" argument of 'int Hello:: get_member()' discards qualifiers [-fpermissive]
Solution
int get_member() const {return member_;}
Should fix it. You can't call a non-const member from a const member as it breaks the 'promise' of const. If you could there would be no guarantee that the object isn't modified during the call.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow