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();
}
Derived*tovoid*and then toBase*that it'll actually point to the right object. - Brian BiBasesubobject at the end of theDerivedobject instead of at the beginning, in which casestatic_cast<Base*>(ptr)likely won't point to theBasesubobject, since it'll point to the beginning of theDerivedobject. - Brian Bi