C++ reference to struct object: as both names alias the same , how do prints change before and after mutation?
#include
struct Tab { short n; };
int main()
{
Tab b; Tab &rb = b;
b.n = 5;
cout << b.n << " " << rb.n << " ";
rb.n = 8;
cout << b.n << " " << rb.n;
return 0;
}
-
AIt will result in a compile time error.
-
BThe program will print the output 5 5 5 8.
-
CThe program will print the output 5 5 8 8.
-
DThe program will print the output 5 5 5 5.
-
EThe program will print the output 5 8 8 8.
Answer
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
Tabhas one membershort n. bis an object;rbis a reference tob.
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