Difficulty: Medium
Correct Answer: The program will print the output 12.
Explanation:
Introduction / Context:
This question explores constructor overload choice when defaults are present, name shadowing inside constructors, the most-vexing parse, and effects of passing by reference. It asks what value is ultimately printed by Display().
Given Data / Assumptions:
CuriousTab(int)
and CuriousTab(int,int)
(the latter has defaults).CuriousTab objCuriousTab(val);
with val = 12
.CuriousTab objTmp();
is a function declaration (most-vexing parse), not an object.SetValue(int& y, float z)
assigns to the member and mutates the caller’s variable.
Concept / Approach:
Overload resolution prefers the exact single-argument match (CuriousTab(int)
) over using a default parameter in the two-argument constructor. Inside that constructor, the parameter name shadows the member, so x = x;
assigns the parameter to itself and leaves the member x
uninitialized (though it will be assigned later). SetValue(val, 3.14f)
sets the member x
to 12 and then casts 3.14f to 3 and stores it back into val
via the reference.
Step-by-Step Solution:
x
remains uninitialized but will be set next.Call SetValue
: assign x = y
→ x = 12
; then y = (int)z
→ caller’s val
becomes 3.Display prints the current member x
, which is 12.
Verification / Alternative check:
Had the two-arg ctor been chosen, x
would become p += 2
. But default-argument overload is not preferred over the exact one-parameter constructor here.
Why Other Options Are Wrong:
Common Pitfalls:
Name shadowing in constructors (x = x;
) and misinterpreting CuriousTab objTmp();
as an object instead of a function declaration.
Final Answer:
The program will print the output 12.
Discussion & Comments