Answer to Question #232347 in C++ for Arup

Question #232347

Write a program to exchange values(swap) between two classes by using friend function(call by reference).


1
Expert's answer
2021-09-02T04:04:43-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS