PROGRAM TO SWAP PRIVATE DATA MEMBER OF TWO DIFFERENT CLASSES USING FRIEND FUNCTION
/*WRITE A PROGRAM TO SWAP PRIVATE DATA MEMBER OF TWO DIFFERENT CLASSES USING FRIEND FUNCTION*/
#include<conio.h>
#include<iostream.h>
class two;
class one
{
intx;
public:
void set value(inti)
{
x=i;
}
void display()
{
cout<<"x="<<x;
};
friend void swap(one,two);
};
classtwo
{
inty;
public:
void set value(intj)
{
y=j;
}
void display()
{
cout<<"y="<<y;
};
friend void swap(one,two);
};
void swap(onea,twob)
{
int temp;
temp=a.x;
a.x=b.y;
b.y=temp;
cout<<"x="<<a.x<<"y="<<b.y;
}
voidmain()
{
one on;
two tw;
cout<<"\nBefore swapping";
on.setvalue(10);
tw.setvalue(20);
on.display();
tw.display();
cout<<"\nAfter swapping";
swap(on,tw);
getch();
#include<conio.h>
#include<iostream.h>
class two;
class one
{
intx;
public:
void set value(inti)
{
x=i;
}
void display()
{
cout<<"x="<<x;
};
friend void swap(one,two);
};
classtwo
{
inty;
public:
void set value(intj)
{
y=j;
}
void display()
{
cout<<"y="<<y;
};
friend void swap(one,two);
};
void swap(onea,twob)
{
int temp;
temp=a.x;
a.x=b.y;
b.y=temp;
cout<<"x="<<a.x<<"y="<<b.y;
}
voidmain()
{
one on;
two tw;
cout<<"\nBefore swapping";
on.setvalue(10);
tw.setvalue(20);
on.display();
tw.display();
cout<<"\nAfter swapping";
swap(on,tw);
getch();
}
----------------------------------------------------------
OUTPUT:-
1 comments
#include
ReplyDeleteusing namespace std;
class Child;
class Parent
{
int num1;
public:
Parent(int n)
{
num1=n;
}
void show()
{
cout<<"Value of Number 1 : "<<num1;
}
friend void swap(Parent &, Child &);
};
class Child
{
int num2;
public:
Child(int n)
{
num2=n;
}
void show()
{
cout<<"Value of Number 2 : "<<num2;
}
friend void swap(Parent &, Child &);
};
void swap(Parent &x, Child &y)
{
int temp = x.num1;
x.num1 = y.num2;
y.num2 = temp;
}
int main()
{
Parent p1(100);
Child c1(200);
cout<<"Before Swapping: "<<endl;
p1.show();
cout<<endl;
c1.show();
swap(p1,c1);
cout<<endl;
cout<<"After Swapping: "<<endl;
p1.show();
cout<<endl;
c1.show();
return 0;
}