Practice mode C++

Why should a base class intended for polymorphic use have a virtual destructor?

Correct answer A. So that deleting a derived object through a base pointer runs the derived destructor

Explanation

If Base has a non-virtual destructor, then delete basePtr on an object of type Derived is undefined behaviour; in practice usually only ~Base runs and resources owned by the derived part leak. Making ~Base virtual ensures the correct destructor chain, ~Derived then ~Base, is called. Constructors can never be virtual, and a virtual destructor does not make the class abstract.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.