Write a program to exchange values(swap) between two classes by using friend function(call by reference).
#include <iostream>
using namespace std;
class A{
private:
int number;
public:
A(int a){
number=a ;
}
friend int getNumberA(A&); //A friend function to return the data member in class A
};
int getNumberA(A&a){
return a.number;
}
class B{
private:
int number;
public:
B(int a){
number=a ;
}
friend int getNumberB(B&); //A function to return the data member in class B
};
int getNumberB(B&b){
return b.number;
}
void swap(A& s1, B& s2)
{
int temp;
int first = getNumberA(s1);
int second = getNumberB(s2);
cout << "\nBefore Swapping: " << first<< " " <<second ;
temp = first;
first = second;
second= temp;
cout << "\nAfter Swapping: " << first << " " << second;
}
//Testing Code
int main()
{
A s1(100);
B s2(90);
swap(s1,s2);
return 0;
}
Comments
Leave a comment