What are friend functions ? Is it possible for a function to be friend of two classes ? If yes then how is it implemented in C++. Explain with suitable example. ---PU-2016 (New Course)
Sep 10, 2018Please refer to the other posts for the defination of friend functions,
Of course, a function can be friend of two classes.
The following example program illustrates the concept.
// prgoram that accesses the private
//properties of the objects of two
//classes class A, and class B
#include<iostream>
using namespace std;
class B;
class A{
private:
char password[10];
public:
void readPass(){
cout<<"Enter Password for A:"<<endl;
cin>>password;
}
//friend function declaration
friend void myFriendFunction(A a, B b);
};
//defination of class B
class B{
private:
char password[10];
public:
void readPass(){
cout<<"Enter Password for B:"<<endl;
cin>>password;
}
//friend function declaration
friend void myFriendFunction(A a, B b);
};
// defination of friend function
void myFriendFunction(A a, B b){
cout<<"Password of A: "<<a.password<<endl;
cout<<"Password of B: "<<b.password<<endl;
}
int main(){
A aa;
B bb;
aa.readPass();
bb.readPass();
myFriendFunction(aa, bb);
return 0;
}
Sample Run:
Enter Password for A: hello1A Enter Password for B: hello2B Password of A: hello1A Password of B: hello2B