In C++ with global ints i and j, a constructor writes to both and prints j. Then main uses references and mixed pre/post operations. What exactly is printed by this program (consider the constructor's output too)? #include<iostream.h> int i, j; class CuriousTab { public: CuriousTab(int x = 0, int y = 0) { i = x; j = x; Display(); } void Display() { cout << j << " "; } }; int main() { CuriousTab objCuriousTab(10, 20); int &s = i; int &z = j; i++; cout << s-- << " " << ++z; return 0; }

Difficulty: Medium

Correct Answer: The program will print the output 10 11 11.

Explanation:


Introduction / Context:
This exercise ties together constructor side effects on globals, a Display call inside the constructor, and later reference-based increments/decrements printed in main. You must include the constructor’s output (printed before main’s cout values) in the final sequence.


Given Data / Assumptions:

  • Constructor sets i=10 and j=10, then prints j and a space.
  • In main: s aliases i, z aliases j.


Concept / Approach:
Process prints chronologically: first the constructor’s Display, then the cout line in main. Carefully apply pre/post increment semantics to s (alias of i) and z (alias of j).


Step-by-Step Solution:

Constructor: i=10, j=10; Display() prints "10 ". Then i++ makes i=11. s-- prints 11 (old i), then i becomes 10. ++z increments j from 10 to 11 and prints 11. Combined output: "10 11 11".


Verification / Alternative check:
Manually substitute i and j in the final cout to confirm the values at each stage.


Why Other Options Are Wrong:
They either add an extra number, miss the constructor print, or misuse pre/post rules.


Common Pitfalls:
Forgetting that s-- prints the old value and that Display already printed once from the constructor.


Final Answer:
The program will print the output 10 11 11.

More Questions from References

Discussion & Comments

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