Search code examples
c++virtual-destructor

C++ Virtual Destructor Crash


I have the following class hierarchy:

class Base  
{  
public:  
    virtual ~Base();  
};  
class Derived : public Base  
{  
public:  
    virtual ~Derived();  
};  
class MoreDerived : public Derived  
{  
public:  
    virtual ~MoreDerived();  
};  

along with an objects

Base* base = new Base();
MoreDerived* obj = new MoreDerived(*base);  

There is a part of code where I need to delete the MoreDerived object using a thread, thus having to cast it to void* first. In the thread, I have

void KillObject(void* ptr)  
{  
    delete static_cast<Base*>(ptr);  
}  

Non of the pointers are NULL, and void* ptr IS a MoreDerived* (or at least a Base*), but the application still crashes...


Solution

  • I think you're thinking of dynamic_cast<void*> which obtains a pointer to a most-derived object.

    You don't need to go through a void* just to delete an object of polymorphic type. Just take whatever pointer you have and delete it, be it a Base* to a MoreDerived object or a MoreDerived*. There is no need for a Kill method.