C++ swapping via pointers to members in two different objects: after Exchange(&objA.x, &objB.y), what prints? #include<iostream.h> class CuriousTab{ public: int x, y; CuriousTab(int xx=10,int yy=20){ x=xx; y=yy; } void Exchange(int*, int*); }; void CuriousTab::Exchange(int *x, int *y){ int t; t=*x; *x=*y; *y=t; } int main(){ CuriousTab objA(30,40), objB(50); objA.Exchange(&objA.x, &objB.y); cout << objA.x << " " << objB.y << endl; }
-
A20 10
-
B30 20
-
C20 30
-
D30 40
-
E50 30
Answer
Correct Answer: 20 30
Explanation
Introduction / Context:This confirms understanding of constructors with defaults, object-to-object member access via pointers, and the standard three-step swap pattern using a temporary.
Given Data / Assumptions:
objA(30,40)⇒x=30, y=40.objB(50)⇒x=50, y=20(defaultyy=20).- We swap
objA.xwithobjB.y.
Concept / Approach:Pass addresses of specific members to perform a cross-object swap.
Step-by-Step Solution:1) Before: objA.x=30, objB.y=20.2) Swap: temp=30; *x = *y sets objA.x=20; *y = temp sets objB.y=30.3) Print: 20 30.
Verification / Alternative check:Print members before and after the call to observe the swap.
Why Other Options Are Wrong:They misplace which members were swapped or assume defaults incorrectly.
Common Pitfalls:Accidentally swapping x with x or y with y instead of cross-swapping.
Final Answer:20 30