Site icon T4Tutorials.com

Example of a function that is friend of multiple classes? C++ Example

Yes, Friend functionality is not restricted to only one class. One function can be a friend of many classes.

#include <iostream>
using namespace std;
class T4Tutorials_2;
class T4Tutorials_1 {
private:
int n1=1;
public:
friend int add(T4Tutorials_1, T4Tutorials_2);
};

class T4Tutorials_2 {
private:
int n2=6;
public:
friend int add(T4Tutorials_1 , T4Tutorials_2);
};
int main()
{
T4Tutorials_1 object1;
T4Tutorials_2 object2;
cout<<"Sum: "<< add(object1, object2);
return 0;
}
int add(T4Tutorials_1 object1, T4Tutorials_2 object2)
{
return (object1.n1 + object2.n2);
}

Output

Sum: 7

Friend functionality is not restricted to only one class
Friend functionality is not restricted to only one class
Friend functionality is not restricted to only one class
Friend functionality is not restricted to only one class
Exit mobile version