In C++ object lifetime management, which special member function is automatically executed when an object goes out of scope or is deleted?

Difficulty: Easy

Correct Answer: destructor

Explanation:

Introduction / Context:C++ guarantees deterministic cleanup for objects through a special member function that runs at the end of an object's lifetime. Understanding which function this is underpins Resource Acquisition Is Initialization (RAII) and exception safety.

Given Data / Assumptions:

  • An automatic (stack) object leaves scope.
  • A dynamically allocated object is deleted via delete or delete[].
  • We assume normal termination and stack unwinding.

Concept / Approach:The destructor (~ClassName) executes when the object's lifetime ends. It should release any resources acquired by the object, such as memory, file handles, sockets, or locks. Constructors initialize; destructors finalize. Virtual destructors enable correct cleanup via base-class pointers in polymorphic hierarchies.

Step-by-Step Solution:1) Create object: Widget w; → constructor runs.2) Scope ends or delete p; is called → destructor ~Widget() runs.3) Inside ~Widget(), free resources and maintain invariants.4) Program proceeds with resources properly released.

Verification / Alternative check:Add logging to ~Widget(). You will observe a call each time an object is destroyed, including in reverse order for multiple objects in the same scope.

Why Other Options Are Wrong:constructor: runs at creation time, not destruction.virtual function: generic term; destructors themselves can be virtual.main: program entry point, unrelated to object teardown.assignment operator: handles assignment between existing objects, not end-of-life.

Common Pitfalls:Forgetting to declare a virtual destructor in a polymorphic base class and deleting derived objects via a base pointer, which leaks resources or produces undefined behavior.

Final Answer:destructor

Discussion & Comments

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