C++ swapping via pointers to members in two different objects: after Exchange(&objA.x, &objB.y), what prints?\n\n#include<iostream.h>\nclass CuriousTab{\npublic:\n int x, y;\n CuriousTab(int xx=10,int yy=20){ x=xx; y=yy; }\n void Exchange(int*, int*);\n};\nvoid CuriousTab::Exchange(int *x, int *y){ int t; t=*x; *x=*y; *y=t; }\nint main(){ CuriousTab objA(30,40), objB(50); objA.Exchange(&objA.x, &objB.y); cout << objA.x << " " << objB.y << endl; }

Difficulty: Easy

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 (default yy=20).
  • We swap objA.x with objB.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

More Questions from Functions

Discussion & Comments

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