Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a derived object via a pointer to its base class

Tags:

c++

I have two classes, base_class and derived_class and the following code:

base_class *ptr = new derived_class;
delete ptr;

Will this code produce a memory leak? If so, how should I deal with it?

like image 429
dreta Avatar asked Jan 07 '12 10:01

dreta


1 Answers

It won't leak the object you are deleting, its memory block will be freed.

If you have not declared the destructor in base_class to be virtual then it will leak any dynamically allocated objects contained within derived_class that rely on the destructor of derived_class being called to free them. This is because if the destructor is not virtual, the derived_class destructor is not called in this case. It also means that destructors of "embedded objects" within derived_class will not automatically be called, a seperate but additional problem, which can lead to further leaks and the non-execution of vital cleanup code.

In short, declare the destructor in base_class to be virtual and you can safely use the technique you have presented.

For a coded example, see:

In what kind of situation, c++ destructor will not be called?

like image 86
ScrollerBlaster Avatar answered Oct 12 '22 22:10

ScrollerBlaster