0

Lets say I have a class Base that has a const and non-const version of the same function, and the non-const version is virtual. Then I have a class Derived that overrides the non-const version. If my Derived variable is const, why does accessing this function fail to compile? I can access the const version through a const base class pointer, but why not through the derived class?

Here is a minimal, verifiable example:

#include <string>

using namespace std;

class Base
{
public:
    virtual string& GetString() = 0;

    const string& GetString() const 
    {
        return const_cast<Base*>(this)->GetString();
    }
};

class Derived : public Base
{
public:
    string& GetString() override { return str; };
private:
    string str = "hello world";
};

int main()
{
    Derived Obj;
    Obj.GetString(); // Compiles correctly

    const Base* BasePtr = new Derived;
    BasePtr->GetString(); // Compiles correctly

    const Derived* DerivedPtr = new Derived;
    static_cast<const Base*>(DerivedPtr)->GetString(); // Compiles correctly

    const Derived ConstObj;
    ConstObj.GetString(); // error: passing ‘const C’ as ‘this’ argument discards qualifiers


    delete BasePtr;
    delete DerivedPtr;
    return 0;
}
pigi5
  • 74
  • 1
  • 10
  • 3
    Does this help? https://stackoverflow.com/questions/888235/overriding-a-bases-overloaded-function-in-c/888313#888313 . Overloading base methods requires you to promote the base methods with a `using` declaration. – parktomatomi Jan 23 '20 at 16:42
  • Thanks, I guess I was being too specific in my search – pigi5 Jan 23 '20 at 16:45

0 Answers0