Monday 19 May 2014

Object swapping using operator overloading

            == operator overloading to swap two objects in c++


#include<conio.h>
#include<iostream>
using namespace std;
class A
{
int a,b;
public:
void get()
{
cout<<"\n enter value for a and b :";
cin>>a>>b;
}
void show()
{
cout<<"\na ="<<a<<" and b ="<<b<<endl;
}
void operator ==(A &c) // swapping of datamembers of two objects;
{
A temp1;
temp1.a=a;
a=c.a;
c.a=temp1.a;

temp1.b=b;
b=c.b;
c.b=temp1.b;
}

};
int main()
{
A o1,o2;
cout<<"\n enter details for first object :";
o1.get();
cout<<"\nenter details for second object :";
o2.get();

cout<<" \nafter swaping of both objects :\n";
o1==o2; // swapping of two objects;

cout<<"\n details of first object:";
o1.show();
cout<<"\n details of second object:";
o2.show();
getch();
return 0;

}

No comments:

Post a Comment