1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. class B { public: ~B() {} }; class D : public B { public…

Added 30 Nov -0001

class B { public: ~B() {} }; class D : public B { public: ~D() {} }; and then delete (B*)new D; is executed. What happens?

  1. Only D's destructor runs, because the dynamic type is D
  2. Undefined behaviour: only B's destructor runs, because B's destructor is not virtual Correct answer
  3. Both destructors run, since destructors are always virtual
  4. A compile error, because a base pointer cannot delete a derived object

Correct answer

B. Undefined behaviour: only B's destructor runs, because B's destructor is not virtual

14 views

MCQSEXAM

Explanation

Virtual destructor is required whenever deletion may happen through a base pointer, because a non-virtual destructor makes the behaviour undefined and in practice skips the derived destructor, leaking its resources. Declaring virtual ~B() makes delete dispatch to ~D() and then ~B(). A class with virtual functions but a non-virtual destructor should not be used polymorphically for ownership.

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