In C++ (old iostream.h style), predict the exact output including the destructor print when member x is altered via pointer re-interpretation.
#include
class CuriousTab {
int x, y;
public:
CuriousTab(int xx) { x = ++xx; }
~CuriousTab() { cout << x - 1 << " "; }
void Display() { cout << --x + 1 << " "; }
};
int main() {
CuriousTab objCuriousTab(5);
objCuriousTab.Display();
int p = (int) &objCuriousTab; // write into first data member (x)
*p = 40; // force x = 40
objCuriousTab.Display(); // destructor runs after main and also prints
return 0;
}
-
A6 6 4
-
B6 6 5
-
C5 40 38
-
D6 40 38
Answer
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 = ++xxwith argument 5. Display()prints--x + 1followed by a space.- Destructor prints
x - 1followed by a space. int p = (int)&objCuriousTabtargets 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