C++ globals and references: follow constructor prints and later mutations—what is the final console output?
#include
int x, y;
class CuriousTabTest {
public:
CuriousTabTest(int xx = 0, int yy = 0)
{
x = xx; y = yy;
Display();
}
void Display() { cout << x << " " << y << " "; }
};
int main()
{
CuriousTabTest obj(10, 20); // prints once in ctor
int &rx = x; int &ry = y;
ry = x; // y = 10
rx = y; // x = 10
cout << rx--; // prints 10 then decrements x to 9
return 0;
}
-
AThe program will print the output 0 0 10.
-
BThe program will print the output 10 20 10.
-
CThe program will print the output 10 20 9.
-
DIt will result in a compile time error.
-
EThe program will print the output 20 10 10.
Answer
Correct Answer: The program will print the output 10 20 10.
Explanation
Introduction / Context:
This problem asks you to combine constructor-time printing, global variables, and references used later in main. The key is that the constructor prints immediately and later streaming of rx-- shows the value before decrement.
Given Data / Assumptions:
- Globals
xandy. - Constructor assigns
x=10,y=20and prints\"10 20 \". - References
rxandryaliasxandy.
Concept / Approach: Post-decrement returns the current value then decrements the object. The intermediate assignments make both globals equal to 10 before the final print.
Step-by-Step Solution: 1) Constructor prints 10 20 . 2) ry = x; sets y=10. 3) rx = y; sets x=10. 4) cout << rx--; prints 10, then decrements x to 9. 5) Combined console output: 10 20 10 (spaces as shown).
Verification / Alternative check: Change the last line to cout << --rx; to see 9 printed instead, matching option C's last number and highlighting the difference between pre and post operators.
Why Other Options Are Wrong: 0 0 10 contradicts constructor assignment; 10 20 9 confuses pre/post decrement; compile error is inapplicable; 20 10 10 swaps constructor values.
Common Pitfalls: Overlooking that the constructor already printed; forgetting post-decrement prints the old value.
Final Answer: 10 20 10