In C++ polymorphic class design, which statement is correct regarding the destructor of a base class that may be deleted through a base pointer? Choose the best practice that prevents resource leaks and undefined behavior.

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:

  • A base class may be used polymorphically (i.e., it has at least one virtual member function or is intended for inheritance).
  • Derived classes may own additional resources that require cleanup in their destructors.
  • Deletion may occur through a base pointer: delete basePtr;



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.


More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion