If a C++ programmer does not explicitly define a destructor for a class, who provides an empty destructor automatically?

Difficulty: Easy

Correct Answer: Compiler

Explanation:


Introduction / Context:
C++ defines a set of special member functions that may be implicitly declared or defined by the compiler to ensure sane object semantics. One of these is the destructor, responsible for cleanup when an object's lifetime ends. This question asks which component supplies a default destructor when you do not write one.


Given Data / Assumptions:

  • No user-declared destructor exists in the class.
  • The build process includes preprocessing, compiling, linking, and loading.
  • We focus on who generates the destructor code.


Concept / Approach:
The C++ compiler implicitly declares and may define a destructor if none is provided. The preprocessor only performs textual substitution; the linker combines object files; main() is just the entry point; the runtime loader maps binaries into memory. None of those create class members. Therefore, the correct answer is the compiler.


Step-by-Step Solution:
1) Omit ~ClassName() in your class.2) The compiler synthesizes a default destructor with empty body semantics appropriate for the class.3) This synthesized destructor destroys members and bases automatically via their destructors.4) Program compiles and links without you writing explicit cleanup code.


Verification / Alternative check:
Compile a trivial class without a destructor; observe that objects can be created and destroyed, and member destructors are invoked automatically.



Why Other Options Are Wrong:
Preprocessor: macro substitution only.Linker/loader/main: do not generate C++ class members.



Common Pitfalls:
Assuming an implicit destructor is noexcept; check exception specifications as needed. Often, user-defined destructors should be marked noexcept to support strong guarantees.



Final Answer:
Compiler

More Questions from Constructors and Destructors

Discussion & Comments

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