C++ constructors: what happens if a class defines only parameterized constructors (no zero-argument/default constructor), but the program attempts to create an object that requires a no-argument constructor?

Difficulty: Easy

Correct Answer: Compile-time error.

Explanation:


Introduction / Context:
In C++ object construction, the presence or absence of a default (zero-argument) constructor controls which forms of object creation are valid. If a class only supplies parameterized constructors and omits a default constructor, any attempt to create an instance without arguments tests your understanding of overload resolution and constructor availability at compile time.


Given Data / Assumptions:

  • The class explicitly defines one or more parameterized constructors.
  • No user-declared default constructor is provided, and no implicitly generated one exists due to the user-declared constructors.
  • The program tries to create an object with syntax that requires a zero-argument constructor (for example, T obj; or new T; or a container default-constructing T).


Concept / Approach:

When you declare any user-defined constructor, the compiler does not implicitly declare a default constructor unless its generation is still permitted by the rules. If none exists and code requires default construction, overload resolution fails during compilation. Because constructors are selected and validated at compile time, the failure is detected before the program can run, eliminating the possibility of a run-time error or exception here.


Step-by-Step Solution:

Identify that the object creation site provides no arguments. Check class interface: only parameterized constructors are available. Attempt overload resolution: no matching constructor taking zero parameters. Compilation fails with a diagnostic: “no matching constructor for initialization.”


Verification / Alternative check:

Provide a user-declared default constructor (T();) or give default values to all parameters of one constructor, making it usable without arguments. Recompile and observe that the error disappears, confirming the compile-time nature of the issue.


Why Other Options Are Wrong:

Preprocessing error: preprocessing does not consider constructors; it only handles directives and macros.

Runtime error / Runtime exception: construction viability is determined before linking and execution, so the program never runs to hit a run-time failure for this cause.


Common Pitfalls:

  • Assuming the compiler will “synthesize” a default constructor even if parameterized ones exist.
  • Confusing default initialization (T t;) with value-initialization (T t{};), both still require an accessible default constructor.


Final Answer:

Compile-time error.

Discussion & Comments

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