Difficulty: Easy
Correct Answer: 10 10 20 20
Explanation:
Introduction / Context:
This program checks understanding of pointer member access in C++. The expression (*p).x
and the shorthand p->x
both access the same data member of the object that p
points to. The code sets the member twice and prints after each assignment to verify aliasing behavior.
Given Data / Assumptions:
p
is obtained via new Tab()
, so the pointer is valid.Tab
has a public integer member x
.
Concept / Approach:
The dereference operator *
yields the object to which a pointer refers. Member access uses .
on an object and ->
on a pointer. Therefore, (*p).x
and p->x
are equivalent lvalues that refer to the same integer member.
Step-by-Step Solution:
1) (*p).x = 10;
stores 10 in the member. 2) The first print outputs 10
twice because both forms read the same member. 3) p->x = 20;
overwrites the same location with 20. 4) The second print outputs 20
twice for the same reason.
Verification / Alternative check:
Replace (*p).x
with p->x
everywhere; observable behavior is unchanged since both are identical in meaning.
Why Other Options Are Wrong:
“Garbage” outputs would require uninitialized reads, which do not occur here. There is no compile-time error since syntax and access specifiers are correct.
Common Pitfalls:
Forgetting to allocate the object before dereferencing; confusing p.x
(invalid for pointers) with p->x
; assuming different storage for the two notations.
Final Answer:
10 10 20 20
Discussion & Comments