In C++ object-oriented programming, what do we call the special member function that is invoked automatically each time an object's lifetime ends (for example, when it goes out of scope or is deleted)?

Difficulty: Easy

Correct Answer: destructor

Explanation:


Introduction / Context:
Resource management in C++ relies heavily on the RAII (Resource Acquisition Is Initialization) idiom. Central to RAII is the special member function that runs automatically when an object's lifetime ends. Knowing its name and role is essential for writing safe, leak-free code that properly closes files, releases memory, and unlocks mutexes.


Given Data / Assumptions:

  • An object's lifetime ends when it goes out of scope, is explicitly deleted, or when program termination destroys static objects.
  • C++ provides special member functions with fixed names and rules: constructors and destructors.
  • We focus on the function that executes at the end of an object's life.


Concept / Approach:

  • The destructor has the class name prefixed with a tilde (~ClassName). It is called automatically to perform cleanup.
  • Constructors initialize objects; destructors finalize and release resources.
  • Destructors can be user-defined or compiler-generated; they may be virtual in polymorphic base classes to ensure correct dynamic dispatch on deletion.


Step-by-Step Solution:

Identify the life-cycle event: object destruction (end of lifetime).Map the event to the C++ special member function responsible: the destructor.Confirm naming convention: ~ClassName(), no return type, no parameters, optionally virtual.Conclude the correct term is 'destructor' rather than any colloquial synonym.


Verification / Alternative check:

Consider std::unique_ptr managing heap memory: when the unique_ptr object is destroyed, its destructor automatically deletes the owned pointer, proving the cleanup role.


Why Other Options Are Wrong:

  • constructor: Runs at object creation, not destruction.
  • destroyer / terminator: Informal, non-standard terms; not C++ keywords or required names.
  • None of the above: Incorrect because ”destructor” is the precise term.


Common Pitfalls:

  • Forgetting to declare a virtual destructor in a polymorphic base class, leading to undefined behavior when deleting through a base pointer.
  • Performing complex logic or throwing exceptions from destructors; exceptions escaping a destructor during stack unwinding call std::terminate.


Final Answer:

destructor

Discussion & Comments

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