Write a program to swap private data members of classes.

0
134

Write a program to swap private data members of classes named as class_a and class_b using friend function.
The program has two classes class_a and class_b with private integer members int a and int b respectively in the two classes. The two classes will have functions indata() and display() to accept private variable value as input and display the same for both the classes.
Declare and Define a function named swap (a friend function) to swap the private integers of these two classes.

using namespace std;
class class_b;
class class_a
{
int a;
public:
void indata(int x)
{
a=x;
}
void display()
{
cout<<a<<endl;
}
friend void swap(class_a &, class_b &)
};
class class_b
{
int b;
public:
void indata(int x)
{
b=x;
}
void display()
{
cout<<b<<endl;
}
friend void swap(class_a &, class_b &)
};
void swap(class_a &m, class_b &n)
{
int temp;
temp = m.a;
m.a = n.b;
n.b = temp;
}
int main() 
{
int x,y;
cin>>x>>y;
class_a obj_a; //object of class_a
class_b obj_b; //object of class_b
obj_a.indata(x); //Callling indata() of class_a
obj_b.indata(y); // calling indata() of class_b
// cout<<"Value of a and b before swapping :"<<endl;;
// obj_a.display(); //Callling display() of class_a
//obj_b.display(); //Callling display() of class_b
swap(obj_a, obj_b); //Callling swap() which is a friend function of both the classes
//cout<<"Value of a and b after swapping :"<<endl;
obj_a.display(); //Callling display() of class_a
obj_b.display(); //Callling display() of class_b
return 0;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here