C++ references and default constructor print: what will this program output when passing pre-incremented and pre-decremented references to the constructor?
#include
class CuriousTab
{
int x, y, z;
public:
CuriousTab(int x = 100, int y = 30, int z = 0)
{
this->x = x;
this->y = y;
this->z = z;
Display();
}
void Display()
{
cout << x << " " << y << " " << z;
}
};
int main()
{
int a = 0, b = 1, c = 2;
int &x = ++a; // a becomes 1, x binds to a
int &y = --b; // b becomes 0, y binds to b
int z = c + b - -c; // z = c + b + c = 4
CuriousTab objCuriousTab(x, y, z);
return 0;
}
-
A1 0 3
-
B1 0 4
-
C1 1 3
-
D1 1 4
-
ECompile-time error
Answer
Correct Answer: 1 0 4
Explanation
Introduction / Context: This question checks evaluation order and reference binding in C++. The constructor of CuriousTab prints its three integer data members immediately. The main function passes references formed via pre-increment and pre-decrement and computes a third argument using unary minus on a negative operand.
Given Data / Assumptions:
- Start with a = 0, b = 1, c = 2.
- x is a reference bound to ++a.
- y is a reference bound to --b.
- z is computed as c + b - -c (that is c + b + c).
- Constructor prints “x y z”.
Concept / Approach: Pre-increment (++a) increments then yields the new value; pre-decrement (--b) decrements then yields the new value. A reference binds to the resulting lvalue, so later reads observe the updated underlying variable. The expression “- -c” is the negation of a negation, effectively +c.
Step-by-Step Solution: 1) ++a: a becomes 1, x refers to a (value 1). 2) --b: b becomes 0, y refers to b (value 0). 3) z = c + b - -c = 2 + 0 + 2 = 4. 4) Constructor receives (1, 0, 4) and immediately prints “1 0 4”.
Verification / Alternative check: Replace “- -c” with “+c” and you still get 4; the output remains unchanged.
Why Other Options Are Wrong: “1 0 3” miscomputes z; “1 1 3/4” wrongly treats y as 1; “Compile-time error” is incorrect because the code is valid with old-style headers.
Common Pitfalls: Forgetting that references alias variables after the increment/decrement, and misreading “- -c”.
Final Answer: 1 0 4