The member is non const, and the member's member function is non const, when it is called on a const member function, it will generate an error, complains about:
error: passing 'const foo' as 'this' argument discards qualifiers [-fpermissive]
code:
// this class is in library code i cannot modify it
class CWork {
public:
const string work(const string& args) { // non const
...
return "work";
}
};
// this is my code i can modify it
class CObject {
private:
CWork m_work; // not const
public:
const string get_work(const string& args) const { // const member function
return m_work.work(args); // error here
}
};
Why is this and how to fix this? Compiler is g++ 5.3.1.
Inside a
constmethod the object (*this) and hence all its members areconst. Think about it, if this wasnt the case then an object beingconstwould not mean anything.Thus
m_workisconstinsideget_workand you can only callconstmethods on it.Make
workalso aconstmethod. There is no apparent reason to make it notconstand by default you should make methodsconst. Only when you need to modify the object make them non-const.In that case you are out of luck. You can only make
get_worknon const too, becauseworkseems to modifym_workhence modifies yourCObjectwhich you cannot do in aconstmethod.