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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#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