class B { public: ~B() {} }; class D : public B { public: ~D() {} }; and then delete (B*)new D; is executed. What happens?
Correct answer
B. Undefined behaviour: only B's destructor runs, because B's destructor is not virtual
14 views
B. Undefined behaviour: only B's destructor runs, because B's destructor is not virtual
14 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.