C++ reference to struct object: as both names alias the same <short>, how do prints change before and after mutation?\n\n#include<iostream.h>\nstruct Tab { short n; };\nint main()\n{\n Tab b; Tab &rb = b;\n b.n = 5;\n cout << b.n << " " << rb.n << " ";\n rb.n = 8;\n cout << b.n << " " << rb.n;\n return 0;\n}

Difficulty: Easy

Correct Answer: The program will print the output 5 5 8 8.

Explanation:


Introduction / Context:
This question reviews how references to objects work in C++. A reference is an alias: any update via the reference affects the same object and is visible through all aliases.


Given Data / Assumptions:

  • Struct Tab has one member short n.
  • b is an object; rb is a reference to b.


Concept / Approach:
When you print b.n and rb.n before mutation, both show the same value. After assigning via rb.n, the shared underlying value changes and both names reflect the new value.


Step-by-Step Solution:
1) Set b.n = 5. 2) Print: b.n and rb.n both yield 5 (same object). 3) Assign rb.n = 8 (mutates the same underlying member). 4) Print again: both names now yield 8.


Verification / Alternative check:
Change the second print to use only b.n; the value is still 8, demonstrating aliasing.


Why Other Options Are Wrong:
5 5 5 8 assumes distinct storage; 5 5 5 5 ignores the mutation; compile error is incorrect because code is valid.


Common Pitfalls:
Assuming a reference is like a pointer requiring dereference with *; forgetting that a reference must be bound on initialization and cannot be reseated.


Final Answer:
5 5 8 8

More Questions from References

Discussion & Comments

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