Polymorphism or inheritance watch out

class B {
char *str;
B(){str = new char[100];}
~B(){delete [] str;}
class D : public B {

B* pB = new D;delete pB; // resource leak cause the base destructor (class B) wasn't call.

Solution 1: The base class "MUST" declare destructor as virtual.

virtual ~B(){delete [] str;}

Solution 2: (a prevention mechanism to C++) By declaring class as final so that can't inherit the class. C++ itself does not have final, concept taken from Java.

E.g. http://www.codeproject.com/cpp/finalclass.asp

or use

class __declspec(novtable) YourClassName


Popular posts from this blog

Clearcase check in/uncheck out all the checked out files script

Duplicating a local copy of project from TFS and making web software client factory to work