When an object's lifetime ends in C++, which special member function of its class is invoked for cleanup?

C++ Programming Constructors and Destructors Difficulty: Easy
Choose an option
  • A
    constructor
  • B
    destructor
  • C
    assignment function
  • D
    copy constructor
  • E
    move constructor

Answer

Correct Answer: destructor

Explanation

Introduction / Context:Object lifetime in C++ begins with construction and ends with destruction. The language provides special member functions to manage both edges. This question asks you to name the function responsible for cleanup.

Given Data / Assumptions:

  • An object is leaving scope or being deleted.
  • Class may hold resources (memory, files, sockets).
  • We want deterministic release of resources.

Concept / Approach:The destructor (~ClassName) runs automatically at the end of an object's lifetime. It releases resources and restores invariants. This is the RAII pattern: acquire resources in constructors; release them in destructors, ensuring exception safety and deterministic cleanup.

Step-by-Step Solution:1) Object is created → constructor establishes state.2) Lifetime ends (scope exit, delete) → destructor executes.3) Destructor closes files, frees memory, and performs other necessary cleanup.4) Program continues with no resource leaks tied to the object.

Verification / Alternative check:Open a file in a class constructor and close it in the destructor. Observe that the file is reliably closed even if exceptions are thrown after construction.

Why Other Options Are Wrong:Constructor: used at creation, not destruction.Assignment / copy/move constructors: manage copying or moving existing objects, not cleanup at end-of-life.

Common Pitfalls:Leaving resource release to manual calls; prefer RAII with destructor-based cleanup for robustness.

Final Answer:destructor

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