एडब्लॉकर मिला (Adblocker Detected)!

नमस्ते! aasansolution.in को पढ़ने के लिए कृपया अपना एडब्लॉकर या Brave Shield को बंद करें।

हमारी मुफ्त सेवाओं को जारी रखने के लिए विज्ञापनों की अनुमति देना ज़रूरी है।

मैंने इसे बंद कर दिया है - रिफ्रेश करें

Tuesday, 1 February 2022

Q. 4. What is a friend function in OOP? write a program in C++ to swap value of two different classes using the friend function?


 

Q. 4. What is a friend function in OOP? write a program in C++ to swap value of two different classes using the friend function? 

Sol. 


What is Friend Function?

A friend function is a function that is declared outside a class but is capable of accessing the private and protected members of the class.


Program to swap values of classes using friend function


/*WRITE A PROGRAM TO SWAP PRIVATE DATA MEMBER OF TWO DIFFERENT CLASSES USING FRIEND FUNCTION*/


#include<iostream.h>

#include<conio.h>

class class_2;

class class_1

 int value1;

 public: 

 void indata(int a) 

 { 

  value1=a; 

 } 

 void display(void) 

 { 

  cout<<value1<<"\n"; 

 } 

 friend void exchange(class_1 &, class_2 &);

};

class class_2

 int value2;

 public: 

 void indata(int a) 

 { 

   value2=a; 

 } 

 void display(void) 

 { 

  cout<<value2<<"\n"; 

 } 

 friend void exchange(class_1 &, class_2 &);

};

void exchange(class_1 &x, class_2 &y)

 int temp = x.value1; 

 x.value1 = y.value2; 

 y.value2 = temp;

}

int main()

 class_1 C1; 

 class_2 C2;

 C1.indata(100); 

 C2.indata(200); 

 cout<<"Values before exchange"<<"\n";

 C1.display(); 

 C2.display(); 

 exchange(C1, C2); 

 cout<<"Values after exchange"<<"\n"; 

 C1.display(); 

 C2.display(); 

 return 0;

}



----------------------------------------------------------

OUTPUT:-



No comments:

Post a Comment