14

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?

3
  • 1
    The code won't compile. I would recommend passing it through a compiler first. Better would be: base_class* ptr = new derived_class(); Commented Jan 7, 2012 at 10:41
  • 4
    If base_class hasn't a virtual destructor this will trigger undefined behavior (§5.3.5/p3) Commented May 6, 2015 at 17:39
  • Refer item 7 of Effective C++ by Scott Meyers (Declare destructors virtual in polymorphic base classes). Commented Mar 8, 2023 at 13:22

1 Answer 1

31

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.