Difficulty: Medium
Correct Answer: 45 22
Explanation:
Introduction / Context:
This question explores side effects of modifying an object's first data member by reinterpreting the object address as an int
and writing to it. While this technique is unsafe and non-portable, it illustrates how member layout affects observed behavior.
Given Data / Assumptions:
x = ++xx
with argument 45, so x
becomes 46.Display()
decrements x
and prints the result.int*
, and the first int
is overwritten with 23.
Concept / Approach:
The first call to Display()
sees x=46
, performs --x
, and prints 45. After forcibly writing 23 into the object's first int
, the second call decrements that value to 22 and prints it. Although y
exists, it is never read or printed.
Step-by-Step Solution:
1) Construct: x=46
. 2) First Display()
: --x
→ 45 printed, x=45
. 3) Raw write: *((int*)&objBT) = 23
→ sets x=23
on typical layouts. 4) Second Display()
: --x
→ prints 22.
Verification / Alternative check:
If the class had padding or different ordering, behavior might vary; on typical ABIs the first member is at offset 0, matching the observed output.
Why Other Options Are Wrong:
Options showing 46 as the first printed value ignore the pre-decrement; showing 23 as a printed value ignores that Display()
decrements before printing.
Common Pitfalls:
Assuming pointer punning like this is portable; forgetting that --x
changes state before printing.
Final Answer:
45 22
Discussion & Comments