{ using Visual Studio 2010 , Win7 }
class Base
{
public:
Base() : terminateCondition(false)
{
//spawn new thread and set entry point to newThreadFunc()
}
virtual ~Base() // edited to say it's virtual.
{
terminateCondition=true;
//wait for thread to join
}
virtual void vfunc() = 0;
static void __stdcall newThreadFunc(void *args)
{
while(!terminateCondition)
pThis->vfunc();
}
volatile bool terminateCondition;
};
class Derived : public Base
{
public:
virtual void vfunc()
{
//Do Something
}
};
Derived* dPtr=new Derived; //now assume pThis is dptr
//later somewhere
delete dPtr;
This code crashes saying pure virtual called. Moving terminateCondition=true to the destructor of Derived prevents this crash. I think i partially get why. Destruction is in reverse order of construction so d’tor of Derived is executed 1st and all functionalities of Derived are destroyed before calling upon the d’tor of Base. In the meantime if pThis->vfunc() is encountered the application would crash. It crashes saying pure virtual called. I could not understand this part. Can someone please explain?
Your Base class destructor needs to be
virtual, Since it is not this code invokes Undefined Behavior.Reference:
C++03 standard: Section 5.3.5/3:
When you call a virtual function through constructor/destructor the dynamic dispatch does not work as you expect it to.
The type of
thisin constructor/destructor is of the type of the class who’s constructor/destructor is being executed. While you expect the dynamic dispatch to call overidden derived class methodDerived::vfunc(), it ends up in a call toBase::vfunc()which does not have a definition and hence results in Undefined Behavior.Reference:
C++03 Standard 10.4/6: