Site icon i2tutorials

CPP- Function Friendly to two classes

Function Friendly to two classes

 

A class-friendly function is defined outside the scope of this class, but it has the right to access all private and protected members of the class. Even though the prototypes of friend functions appear in the class definition, friends are not member functions. 

We can define an identical function adapted to two or more classes.

 

For Example,

#include <iostream>
using namespace std;
class B; // forward declaration
class A {
 private:
 int data1;
 public:
 A() { data1 = 5;}
 friend int func(A , B); //friend function Declaration in class A
};
class B {
 private:
 int data2;
 public:
 B(){data2=9; }
 friend int func(A , B); //friend function Declaration in class B
};
int func(A d1,B d2)
{
//Function func() is the friend function of both classes A and B.
//So, the private data of both class can be accessed from this function.
 return (d1.data1+d2.data2);
}
int main()
{
 A a;
 B b;
 cout<<"TOTAL= "<<func(a,b);
 return 0;
}

 

Output:

Exit mobile version