C++ (constructor overload resolution) — which constructor is called for a character literal created via new, and what is printed?
#include
class CuriousTab {
int x;
public:
CuriousTab(short) { cout << "Short" << endl; }
CuriousTab(int) { cout << "Int" << endl; }
CuriousTab(char) { cout << "Char" << endl; }
~CuriousTab() { cout << "Final"; }
};
int main() {
CuriousTab* ptr = new CuriousTab('B');
return 0;
}
Assume no delete is performed.
-
AThe program will print the output Short .
-
BThe program will print the output Int .
-
CThe program will print the output Char .
-
DThe program will print the output Final .
-
ENone of the above
Answer
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 .