Difficulty: Medium
Correct Answer: 6 40 38
Explanation:
Introduction / Context:
This C++ snippet (legacy iostream.h
) tests object initialization, prefix decrement side effects, type-punning through a raw pointer, and destructor timing. It also checks whether you understand that the destructor's output appears at program end, after the two Display calls.
Given Data / Assumptions:
x = ++xx
with argument 5.Display()
prints --x + 1
followed by a space.x - 1
followed by a space.int p = (int)&objCuriousTab
targets the first data member (x
) in typical layouts.
Concept / Approach:
Track x
precisely across construction, method calls, the raw write via p
, and destruction. The first member write is undefined-behavior in standard terms but commonly maps to x
in such questions; we follow that conventional intent for this MCQ.
Step-by-Step Solution:
1) Construction: parameter 5 ⇒ x = ++5 = 6
.2) First Display()
: computes --x + 1
. Prefix decrement makes x = 5
, printed value is 5 + 1 = 6
. Now x
remains 5.3) Raw overwrite: *p = 40
⇒ set x = 40
.4) Second Display()
: --x + 1
⇒ x = 39
, print 40
. Now x = 39
.5) Destructor: prints x - 1 = 38
.
Verification / Alternative check:
Insert additional prints of x
after each step to confirm transitions: 6 → 5 → 40 → 39 → destructor uses 39.
Why Other Options Are Wrong:
They mishandle the prefix decrement effect or ignore the pointer overwrite before the second call.
Common Pitfalls:
Assuming --x + 1
leaves x
unchanged; prefix decrement changes state.
Final Answer:
6 40 38
Discussion & Comments