Polymorphism or inheritance watch out

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

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.
e.g.

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

Comments

Popular posts from this blog

Outlook : "operation failed, object could not be found. " when trying to close a PST.

Troubleshooting Outlook Express (IMAP, POP3, HTTP, NEWS) with the log file

MSSQL GROUP_CONCAT