What is the main purpose of a virtual destructor in C++?

Options

  • A. To prevent creation of objects
  • B. To ensure proper destruction through a base-class pointer
  • C. To make constructors execute twice
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. To ensure proper destruction through a base-class pointer

Detailed Explanation

Answer: To ensure proper destruction through a base-class pointer

A virtual destructor is important when a derived object may be deleted through a pointer to its base class.

If the base destructor is virtual, destruction occurs correctly through the inheritance hierarchy, allowing the derived-class destructor to execute before the base-class destructor.