C++ special members: the function whose name is the class name prefixed with a tilde (~) is called what?

Difficulty: Easy

Correct Answer: destructor

Explanation:


Introduction / Context:
C++ provides special member functions that govern object lifetime. A function spelled with the class name prefixed by a tilde (~) is one of these special members and is responsible for cleanup when an object's lifetime ends. This question checks recognition of that naming convention and its role in RAII (Resource Acquisition Is Initialization).


Given Data / Assumptions:

  • Spelling: ~ClassName()
  • No return type and no parameters are allowed.
  • Invoked automatically at the end of an object's lifetime.


Concept / Approach:

The member named ~ClassName() is the destructor. It performs finalization such as releasing memory, closing file handles, unlocking mutexes, or logging. The constructor, by contrast, shares the class name without the tilde and initializes the object. Recognizing the destructor’s signature is foundational for writing exception-safe, leak-free code in C++.


Step-by-Step Solution:

Recall naming: constructor → ClassName(...); destructor → ~ClassName(). Recall semantics: constructor runs at creation; destructor runs at scope exit or delete. Match to options: “destructor.” Confirm: no return type; cannot be overloaded; can be virtual.


Verification / Alternative check:

Instrument ~ClassName() with a print; observe calls when objects go out of scope, when vectors shrink, or when delete p; is executed for dynamically allocated objects with virtual destructors where needed.


Why Other Options Are Wrong:

constructor: no tilde and runs at creation.

function/object: too generic and do not identify the special cleanup role.


Common Pitfalls:

  • Forgetting to make base-class destructors virtual when deleting through base pointers.
  • Assuming destructors can have parameters or return types—they cannot.


Final Answer:

destructor

Discussion & Comments

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