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.

How to transfer app and data from old iPhone to new iPhone for model IOS17 and IOS18 above.

Tips on how to use IBM iNotes (web client) on emailing or scheduling - Like copy tables from Excel or checking for user id (windows logon id) through email address