In C++, a constructor taking int& parameters increments the arguments: what is printed?
#include
class CuriousTabTest {
public:
CuriousTabTest(int &x, int &y) { x++; y++; }
};
int main() {
int a = 10, b = 20;
CuriousTabTest objBT(a, b);
cout << a << " " << b;
return 0;
}
-
A10 20
-
B11 21
-
CGarbage Garbage
-
DIt will result in a compile time error.
Answer
Correct Answer: 11 21
Explanation
Introduction / Context: This question checks understanding of references passed to a constructor and side effects on the original variables a and b when they are modified by reference within the constructor body.
Given Data / Assumptions:
- Constructor parameters are int& (lvalue references).
- Inside the constructor: x++ and y++.
- a = 10 and b = 20 before construction.
Concept / Approach: When int& parameters are used, the constructor receives aliases to a and b. Any modification (like ++) directly changes the original variables. Therefore, after construction, a == 11 and b == 21, and cout prints those updated values.
Step-by-Step Solution:
Bind x → a, y → b.Execute x++ → a becomes 11.Execute y++ → b becomes 21.cout prints "11 21".Verification / Alternative check: Changing the constructor to take values (int x, int y) would not change a and b; the program would then print 10 20. References are the key to mutation here.
Why Other Options Are Wrong:
- 10 20: would be correct only if parameters were passed by value.
- Garbage Garbage: no uninitialized use occurs.
- Compile time error: code is valid for classic iostream.h.
Common Pitfalls: Confusing pass-by-value with pass-by-reference; expecting constructor parameters to be copies by default.
Final Answer: 11 21