C++ (constructor overload resolution) — which constructor is called for a character literal created via new, and what is printed?\n\n#include<iostream.h>\nclass CuriousTab {\n int x;\npublic:\n CuriousTab(short) { cout << "Short" << endl; }\n CuriousTab(int) { cout << "Int" << endl; }\n CuriousTab(char) { cout << "Char" << endl; }\n ~CuriousTab() { cout << "Final"; }\n};\nint main() {\n CuriousTab* ptr = new CuriousTab('B');\n return 0;\n}\n\nAssume no delete is performed.

Difficulty: Easy

Correct Answer: The program will print the output Char .

Explanation:


Introduction / Context:
This question checks C++ overload resolution and object lifetime when allocating with new without a corresponding delete. Multiple constructors accept integral-like parameters, and a character literal is passed. Which overload is a best match?


Given Data / Assumptions:

  • Overloads: (short), (int), and (char).
  • Call is new CuriousTab('B').
  • No delete; therefore the destructor message "Final" will not be printed in this run.


Concept / Approach:
Overload resolution prefers the exact match over promotions or conversions. The argument 'B' has type char, so the constructor CuriousTab(char) is an exact match. Short or int would require a conversion/promotion that is strictly worse than an exact match.


Step-by-Step Solution:

1) Identify parameter types: short, int, char.2) Argument is char → exact match to (char).3) The chosen constructor prints "Char".4) The allocated object is leaked (intentionally here), so the destructor is not called; "Final" does not appear.


Verification / Alternative check:
Change the literal to 66 (an int) and you will see "Int". Use (short)'B' to force "Short".


Why Other Options Are Wrong:

  • Short / Int: Not selected because an exact char match exists.
  • Final: Destructor is not invoked without delete.
  • None of the above: A listed option is correct.


Common Pitfalls:
Confusing integral promotions with exact matches, and expecting destructors to run for leaked objects at program end.


Final Answer:
The program will print the output Char .

More Questions from Constructors and Destructors

Discussion & Comments

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