2
votes

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();
}
1
Works fine for me (derived method is called). However I believe what you are trying to do is actually undefined behaviour, because the standard does not appear to guarantee that if you convert Derived* to void* and then to Base* that it'll actually point to the right object.Brian Bi
For example, the compiler is allowed to put the Base subobject at the end of the Derived object instead of at the beginning, in which case static_cast<Base*>(ptr) likely won't point to the Base subobject, since it'll point to the beginning of the Derived object.Brian Bi

1 Answers

3
votes

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.