Original Post
OK, here's the situation: I have a virtual member function with its const overload in a Base class and a Derived class in which that virtual function is overridden: Now, this code works as expected as long as a Derived object is pointed to by a Base pointer, but as soon as this Derived object is pointed to by a Derived pointer, the second, non-const function is hidden, meaning that all non const objects of Derived fail to call Get()?! So, So at first I thought it has something to do with the Derived Get() function hiding the non virtual, non-const Get() in the base, but astonishingly even making the second non-const function virtual won't help a bit which strikes me as odd. The only solution that I've found to make this code work is to somehow redefine the function in the Derived class, be it by redefining the virtual function in the derived class or simply making it pure virtual in an effort to force all subclasses implement it. Now why is that so?! Thanks
struct Type {
};
class Base {
public:
virtual const Type& Get() const = 0;
Type& Get() { return const_cast< Type& >(static_cast< const Base& >(*this).Get()); }
};
class Derived : public Base {
public:
virtual const Type& Get() const { return type; }
private:
Type type;
};
// This works fine
Base* pBase = new Derived;
Type& type = pBase->Get();
// This fails to compile
Derived* pDerived = new Derived;
Type& type = pDerived->Get();
// But then this works fine
Derived* pDerived = new Derived;
const Type& type = pDerived->Get();