C++ object state tampering via pointer cast: trace the prints before and after writing into the object memory.
#include
class CuriousTabTeam
{
int x, y;
public:
CuriousTabTeam(int xx)
{
x = ++xx;
}
void Display()
{
cout<< --x << " ";
}
};
int main()
{
CuriousTabTeam objBT(45);
objBT.Display();
int p = (int)&objBT;
p = 23;
objBT.Display();
return 0;
}
-
A45 22
-
B46 22
-
C45 23
-
D46 23
-
EIt will report a compile-time error
Answer
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:
- Constructor sets
x = ++xxwith argument 45, soxbecomes 46. Display()decrementsxand prints the result.- The object is then reinterpreted as
int*, and the firstintis 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