Search code examples
c++g++constantsmember-functionsfunction-qualifier

calling non-const function on non-const member in const function


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.


Solution

  • Inside a const method the object (*this) and hence all its members are const. Think about it, if this wasnt the case then an object being const would not mean anything.

    Thus m_work is const inside get_work and you can only call const methods on it.

    Make work also a const method. There is no apparent reason to make it not const and by default you should make methods const. Only when you need to modify the object make them non-const.

    it's in library i cannot change it.

    In that case you are out of luck. You can only make get_work non const too, because work seems to modify m_work hence modifies your CObject which you cannot do in a const method.