C++ (constructor selection, shadowing, and references) — determine the output after calling SetValue and Display. #include<iostream.h> class CuriousTab { int x; float y; public: CuriousTab(int x) { x = x; } CuriousTab(int p = 0, int q = 10) { x = p += 2; y = q * 1.0f; } void SetValue(int &y, float z) { x = y; y = (int)z; } void Display(void) { cout << x; } }; int main() { int val = 12; CuriousTab objCuriousTab(val); CuriousTab objTmp(); objCuriousTab.SetValue(val, 3.14f); objCuriousTab.Display(); return 0; } What is printed?

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:

  • Two constructors: CuriousTab(int) and CuriousTab(int,int) (the latter has defaults).
  • Call 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:

Select one-arg ctor: member x remains uninitialized but will be set next.Call SetValue: assign x = yx = 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:

  • 2: Misreads the second constructor as selected.
  • Errors: The program compiles and runs (with legacy headers).

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.

More Questions from Functions

Discussion & Comments

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