C++ references and default constructor print: what will this program output when passing pre-incremented and pre-decremented references to the constructor?\n\n#include<iostream.h>\nclass CuriousTab\n{\n int x, y, z;\npublic:\n CuriousTab(int x = 100, int y = 30, int z = 0)\n {\n this->x = x;\n this->y = y;\n this->z = z;\n Display();\n }\n void Display()\n {\n cout << x << " " << y << " " << z;\n }\n};\nint main()\n{\n int a = 0, b = 1, c = 2;\n int &x = ++a; // a becomes 1, x binds to a\n int &y = --b; // b becomes 0, y binds to b\n int z = c + b - -c; // z = c + b + c = 4\n CuriousTab objCuriousTab(x, y, z);\n return 0;\n}

Difficulty: Medium

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

More Questions from Functions

Discussion & Comments

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