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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It won’t leak the object you are deleting, its memory block will be freed.
If you have not declared the destructor in
base_classto be virtual then it will leak any dynamically allocated objects contained withinderived_classthat rely on the destructor ofderived_classbeing called to free them. This is because if the destructor is not virtual, thederived_classdestructor is not called in this case. It also means that destructors of “embedded objects” withinderived_classwill 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_classto 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?