Difficulty: Easy
Correct Answer: Destructor of base class should always be virtual.
Explanation:
Introduction / Context:
When designing inheritance hierarchies in C++, objects are often manipulated via base-class pointers or references. If you delete a derived object through a base pointer, the correct destructor must run to release all acquired resources. This question targets the essential rule that enables safe polymorphic destruction.
Given Data / Assumptions:
Concept / Approach:
Declaring the base-class destructor as virtual ensures dynamic dispatch on destruction. With a virtual destructor, delete basePtr first calls the most-derived destructor, then unwinds through base classes, guaranteeing complete cleanup and preventing leaks or partial destruction.
Step-by-Step Solution:
1) Declare: struct Base { virtual ~Base() {} };2) Derive: struct Derived : Base { ~Derived() override { /* free derived resources / } };3) Allocate polymorphically: Base p = new Derived();4) Delete via base: delete p; → calls Derived::~Derived() then Base::~Base().
Verification / Alternative check:
Add logging in both destructors; observe that the derived destructor executes first. Removing virtual causes only Base::~Base() to run when deleting through a base pointer, which is unsafe.
Why Other Options Are Wrong:
Static/private/inline-only: none of these access or linkage attributes provide dynamic dispatch; they do not solve polymorphic deletion.“Should not be virtual”: incorrect and dangerous in polymorphic contexts.
Common Pitfalls:
Forgetting to mark a polymorphic base destructor virtual leads to undefined behavior when deleting through base pointers. Conversely, making every destructor virtual needlessly can add slight overhead; do it for polymorphic bases.
Final Answer:
Destructor of base class should always be virtual.
Discussion & Comments