Why would the compiler complain at the indicated line?
class C
{
std::string s;
public:
C() { s = "<not set>";}
~C() {}
void Set(const std::string ss) { s=ss; }
const std::string Get() { return s; }
C &operator=(const C &c) { Set(c.Get()); return *this; }
//error: passing ‘const C’ as ‘this’ argument of ‘const string C::Get()’
// discards qualifiers [-fpermissive]
//C &operator=(C &c) { Set(c.Get()); return *this; } <-- works fine
};
You need to declare the function
Get()to beconst:Even though
Get()doesn’t change any member values, the compiler is instructed to only let you call functions that are explicitly labeledconst.gcc is instructing you that you can override it’s complaint by using the argument
-fpermissive; however, it’s generally better not to do this (or else why declare anythingconstat all?). Generally, it’s better to make sure every member function called on aconstparameter is aconstmember function.This article concerning Const Correctness is very interesting.