C++ (overload resolution with char literal among short/int/float constructors) — which message is printed?
#include
class CuriousTab {
int x;
public:
CuriousTab(short) { cout << "Short" << endl; }
CuriousTab(int) { cout << "Int" << endl; }
CuriousTab(float) { cout << "Float" << endl; }
~CuriousTab() { cout << "Final"; }
};
int main(){ CuriousTab* ptr = new CuriousTab('B'); return 0; }
Assume there is no delete.
-
AThe program will print the output Short .
-
BThe program will print the output Int .
-
CThe program will print the output Float .
-
DThe program will print the output Final .
-
ENone of the above
Answer
Correct Answer: The program will print the output Int .
Explanation
Introduction / Context:With overloads for short, int, and float, a character literal is passed. C++ applies standard conversion sequences and ranks them to choose the best overload. The destructor message will not appear because the allocated object is never deleted.
Given Data / Assumptions:
- Overloads: (short), (int), (float).
- Argument: char literal 'B'.
- No delete → destructor not called.
Concept / Approach:Integral promotions promote types narrower than int to int (or unsigned int). char is promoted to int as part of the integral promotions. A promotion to int is a better conversion sequence than a conversion to short (which is not a promotion) or to float (a floating conversion). Therefore, the (int) constructor is selected and prints "Int".
Step-by-Step Solution:
1) Identify viable overloads: all three are viable.2) Rank conversions: char → int (integral promotion) is best.3) Selected overload prints "Int".4) No destructor call is made; "Final" will not be printed.Verification / Alternative check:Cast to (short)'B' to force "Short"; cast to 66.0f to see "Float".
Why Other Options Are Wrong:
- Short/Float: Worse conversion ranks than promotion to int.
- Final: Requires delete or scope exit for an automatic object.
Common Pitfalls:Assuming char selects the char overload (which does not exist here) or that short is preferred for small integers over int.
Final Answer:The program will print the output Int .