1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. Why should a base class destructor usually be virtual when…

Added 30 Nov -0001

Why should a base class destructor usually be virtual when objects are deleted through base pointers?

  1. So delete can free the object without a type check
  2. So the derived destructor also runs during delete Correct answer
  3. So the destructor can be called twice safely
  4. So the base object is never actually destroyed

Correct answer

B. So the derived destructor also runs during delete

18 views

MCQSEXAM

Explanation

Deleting through a base pointer with a non-virtual destructor is undefined behaviour and typically skips the derived destructor, leaking whatever the derived class allocated. A virtual destructor makes delete dispatch to the most-derived destructor and unwind the chain correctly. A useful rule is that any class with at least one virtual function should also declare its destructor virtual.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs