C++ references passed twice (same object): what will the method print when both parameters alias the same int?
#include
class CuriousTab {
int x, y;
public:
void SetValue(int &xx, int &yy)
{
x = xx++;
y = yy;
cout << xx << " " << yy;
}
};
int main()
{
int x = 10;
int &y = x;
CuriousTab obj;
obj.SetValue(x, y);
return 0;
}
-
AThe program will print the output 10 10.
-
BThe program will print the output 10 11.
-
CThe program will print the output 11 10.
-
DThe program will print the output 11 11.
-
EIt will result in a compile time error.
Answer
Correct Answer: The program will print the output 11 11.
Explanation
Introduction / Context:
This test checks aliasing: both reference parameters xx and yy refer to the same underlying variable. You must carefully track side effects of xx++ and how they affect yy since it is another reference to the same object.
Given Data / Assumptions:
xis 10 andyis a reference tox.SetValuereceives(x, y), so both parameters alias the same int.
Concept / Approach: Post-increment returns the old value but increments the object afterward. Since yy is another alias of the same object, it observes the updated value by the time it is assigned and printed.
Step-by-Step Solution: 1) Entering SetValue: underlying value is 10. 2) x = xx++; stores 10 into the member x, then increments the underlying variable to 11. 3) y = yy; stores 11 into the member y. 4) cout << xx << " " << yy; prints 11 11 because both references now see 11.
Verification / Alternative check: If yy had been a different variable, the printed pair would have been 11 and that other variable's untouched value.
Why Other Options Are Wrong: 10 10 / 10 11 / 11 10 ignore the post-increment's side effect and aliasing. Compile error: Code is valid.
Common Pitfalls: Assuming parameters are independent; forgetting order: store old value into member first, then increment happens, then copy into the other member.
Final Answer: 11 11