C++ pointers and member access: what exactly is printed, and why do (*p).x and p->x show the same value?
#include
class Tab
{
public:
int x;
};
int main()
{
Tab *p = new Tab();
(*p).x = 10;
cout<< (*p).x << " " << p->x << " " ;
p->x = 20;
cout<< (*p).x << " " << p->x ;
return 0;
}
-
A10 10 20 20
-
BGarbage garbage 20 20
-
C10 10 Garbage garbage
-
DGarbage garbage Garbage garbage
-
EIt will report a compile-time error
Answer
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:
pis obtained vianew Tab(), so the pointer is valid.Tabhas a public integer memberx.- Two prints occur: first after writing 10, then after writing 20.
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