Answer to Question #226441 in C++ for Jack

Question #226441

Write a program to swap the data members in two objects, using pass by reference for objects.


1
Expert's answer
2021-08-16T01:06:22-0400
#include <iostream>
 
using namespace std;
 
class Swap {
 
    int temp, a, b;
 
public:

    Swap(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

    friend void swap(Swap&);
};

void swap(Swap& s1)
{

    cout << "\nBefore Swapping: " << s1.a << " " << s1.b;

    s1.temp = s1.a;
    s1.a = s1.b;
    s1.b = s1.temp;
    cout << "\nAfter Swapping: " << s1.a << " " << s1.b;
}
 
int main()
{
    Swap s(3, 9);
    swap(s);
    return 0;
}
Output:
Before Swapping: 3 9
After Swapping: 9 3

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Jack
16.08.21, 08:36

Thanks a lot !!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS