Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Derived Class method from a Void Pointer cast to a Base Object

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();
}
like image 737
user3418519 Avatar asked Nov 20 '25 01:11

user3418519


1 Answers

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.

like image 114
David Schwartz Avatar answered Nov 21 '25 15:11

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!