I want to call an overridden method in a derived class from a void pointer. This fails at runtime because the virtual Base::foo() method is invoked, rather than Derived::foo(). This is how the relevant code works:
Class Base
{
public:
Base();
virtual void foo() = 0;
}
Class Derived: public Base
{
public:
Derived();
void foo();
}
int main()
{
Derived* dv = new Derived();
void* ptr = dv;
static_cast<Base*>(ptr)->foo();
}
There's no way this can work other than by luck. Since this is a static_cast, the conversion must be known at compile time. But because the pointer is a void *, there's no way the compiler can know how the pointer needs to converted to point to the instance of the base inside the derived.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With