C++ object scope: when an object goes out of scope, which special member function is invoked automatically?

Difficulty: Easy

Correct Answer: The default destructor of the object is called.

Explanation:


Introduction / Context:
C++ relies on deterministic destruction (RAII) to release resources such as memory, files, sockets, and locks. Understanding which function runs at scope exit is essential for writing safe code that cleans up reliably, even when exceptions occur.


Given Data / Assumptions:

  • An automatic (stack) object leaves scope due to normal flow, return, or exception.
  • No custom “parameterized” destructors exist in C++; destructors take no parameters.
  • We focus on the automatic invocation that happens at scope exit.


Concept / Approach:

When an object’s lifetime ends (e.g., the block closes), C++ automatically calls its destructor. There is no such thing as a parameterized destructor; the language grammar forbids parameters. The constructor runs at object creation, not at destruction. Therefore, the correct choice is that the object’s (default) destructor is called at scope exit, ensuring cleanup of the object and its subobjects in reverse order of construction.


Step-by-Step Solution:

Define an object inside a block → constructor runs at definition. Exit the block → destructor runs automatically. Members and bases are destroyed automatically in reverse order. Any owned resources are released in the destructor body.


Verification / Alternative check:

Instrument the destructor to log a message. You will see it triggered at scope exit or on delete for dynamically allocated objects; constructors never run at scope exit.


Why Other Options Are Wrong:

Default constructor at scope exit: constructors initialize, not finalize.

Parameterized destructor: invalid concept in C++.

None of the above: wrong because the destructor is indeed called.


Common Pitfalls:

  • Forgetting virtual destructors in polymorphic bases, causing leaks via base pointers.
  • Assuming garbage collection semantics; C++ uses deterministic destruction.


Final Answer:

The default destructor of the object is called.

More Questions from Constructors and Destructors

Discussion & Comments

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