Swapping the data members of two classes using friend function.
swapping the data members of two classes using friend function.
#include<iostream.h>
#include<conio.h>
class second; // Forward declaration to satisfy the compiler about class B
class first
{ int a ;
void get()
{ cout<<"enter the value of a:";
cin>>a;
}
friend void swap ( first &,second &) ;
};
class second
{
int b ;
void get()
{ cout<<"enter the value of b:";
cin>>b;
}
friend void swap ( first &,second &);
};
void swap ( first &ob1,second &ob2 )
{ ob1.get();
ob2.get();
int temp;
temp = ob1.a ;
ob1.a = ob2.b ;
ob2.b = temp ;
cout<<"a="<<ob1.a<<"\nb="<<ob2.b;
}
void main()
{
clrscr();
first ob1;
second ob2;
swap(ob1,ob2) ;
getch();
}
Labels: C++