0

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]

Ford Prefect
  • 107
  • 4

1 Answers1

3
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.

qeadz
  • 1,476
  • 1
  • 9
  • 17
  • 1
    Actually, you can, you just have to promise to the compiler that it's all right (casting). Reneging on the promise is punished with UB. – Deduplicator Apr 10 '14 at 23:15
  • You are correct that the result of calling a non-const member from a const can be achieved through casting. I'm glad you pointed it out - it's good for readers of this question to know. However I strongly feel it should be added that changing the cv qualifiers on something needs very careful consideration before being done. If at all possible, avoid doing it. – qeadz Apr 11 '14 at 00:53