C++ pointers and member access: what exactly is printed, and why do (*p).x and p->x show the same value?\n\n#include<iostream.h>\nclass Tab\n{\n public:\n int x;\n};\nint main()\n{\n Tab *p = new Tab();\n\n (*p).x = 10;\n cout<< (*p).x << " " << p->x << " " ;\n\n p->x = 20;\n cout<< (*p).x << " " << p->x ;\n\n return 0;\n}

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.
  • 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

More Questions from Objects and Classes

Discussion & Comments

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