Difficulty: Easy
Correct Answer: Yes
Explanation:
Introduction / Context:
Destructors are special member functions that run when an object's lifetime ends. In polymorphic class hierarchies, deleting objects through a base pointer requires the correct destructor to run. This question checks whether a destructor itself can be declared virtual and why that matters.
Given Data / Assumptions:
Concept / Approach:
Yes—C++ allows declaring a destructor as virtual. When a base destructor is virtual, delete basePtr triggers dynamic dispatch so that the derived destructor executes first, followed by base destructors up the chain. This prevents resource leaks and undefined behavior when a derived class owns additional resources.
Step-by-Step Solution:
1) Declare in base: virtual ~Base() {}.2) Derive: struct Derived : Base { ~Derived() override { /* release / } };3) Create: Base p = new Derived();4) Delete: delete p; → calls Derived::~Derived() then Base::~Base().
Verification / Alternative check:
Instrument destructors with logging; observe derived then base order during deletion via a base pointer when the base destructor is virtual.
Why Other Options Are Wrong:
No: incorrect—virtual destructors are fully supported.Only for abstract bases / only if other virtuals exist: unnecessary restrictions; you can (and often should) make the base destructor virtual whenever the class is intended for polymorphic use.Compiler-dependent: the behavior is standardized.
Common Pitfalls:
Forgetting a virtual destructor in a polymorphic base causes only the base part to be destroyed when deleting through a base pointer, leaking derived resources.
Final Answer:
Yes
Discussion & Comments