This is what I’m trying to do and I can’t:
#include <string>
using namespace std;
class A {
public:
bool has() const { return get().length(); }
string& get() { /* huge code here */ return s; }
private:
string s;
};
The error I’m getting is:
passing ‘const A’ as ‘this’ argument of
‘std::string& A::get()’ discards qualifiers
I understand what the problem is, but how can I fix it? I really need has() to be const. Thanks.
Add a second overload of
get():That will be called on a
consttyped object of classA.In practice, I prefer adding only
const-typed accessors, and then keeping modifications entirely internal to the class or even avoid them entirely. For example, that means having a methodDoUpdateLabel(){/*do something with s*/}rather than expose the internals. That has the nice side effect that you can avoid duplicating accessors in many cases.If you absolutely must have modification via accessors and you also don’t want an extra const wrapper, you can use
const_cast<>:However, if
get()has side-effects andhas()is declaredconst, it’s questionable whether this is behavior you really want.