In C++ (old iostream.h style), predict the exact output including the destructor print when member x is altered via pointer re-interpretation.\n\n#include<iostream.h>\nclass CuriousTab {\n int x, y;\npublic:\n CuriousTab(int xx) { x = ++xx; }\n ~CuriousTab() { cout << x - 1 << " "; }\n void Display() { cout << --x + 1 << " "; }\n};\nint main() {\n CuriousTab objCuriousTab(5);\n objCuriousTab.Display();\n int p = (int) &objCuriousTab; // write into first data member (x)\n *p = 40; // force x = 40\n objCuriousTab.Display(); // destructor runs after main and also prints\n return 0;\n}

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:

  • Constructor sets x = ++xx with argument 5.
  • Display() prints --x + 1 followed by a space.
  • Destructor prints 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 + 1x = 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

More Questions from Constructors and Destructors

Discussion & Comments

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