Wednesday, May 6, 2009

destructor of interface derived class will never get called

interface struct in C++ is a structure contained only pure virtual functions. no data member shall be declared in interface struct. and because of this no constructor and destructor needed. 

here come the pitfall, consider this

struct IBase
{
virtual void doSomething() = 0;
}

class Derived : public IBase
{
Derived() { text = new char[64]; }
virtual ~Derived() { delete [] text; }

virtual void doSomething() { printf("%s", text);
}

IBase *obj = new Derived();
delete obj;

It was looking perfectly fine to me, until i placed a break point in the derived class destructor. one of the solution is to add a virtual destructor to IBase, but this is ugly and unbalance. the solution I adopted was use self made init() and uninit() insteads.

No comments: