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;
}