Thursday, October 16, 2014

write a program to swap two values between two classes by passing object as reference using friend function in c++

#include<iostream.h>
#include<conio.h>
class xyz;
class abc
{

public:

int x;

void get_x(int a)
{

x=a;
}
void show_x()
{
cout<<"\nx = "<<x;
}

};
class xyz
{

friend void swap(abc &,xyz &);

int y;

public:

void get_y(int b)
{

y=b;
}
void show_y()
{
cout<<"\n y = "<<y;
}

friend void swap(abc &,xyz &);
};
void swap(abc &a1,xyz &x1)
{
int t; t=a1.x; a1.x=x1.y; x1.y=t;
}
void main()
{
clrscr(); abc a2; xyz x2;
a2.get_x(5);
x2.get_y(10);
cout<<"\n Before swapping x and y are ";

a2.show_x(); x2.show_y(); swap(a2,x2);
cout<<"\n After swapping x and y are ";
a2.show_x(); x2.show_y(); getch();
}

Output:

Before swapping x and y are x = 5
y = 10
After swapping x and y are x = 10
y = 5


No comments: