Friend function in c++ oop with examples
Friend function and friend classes in c++ oop with examples.
In this tutorial, we will learn about the followings;
- Friend function and friend classes in c++ oop
- Example of Friend function and friend classes in c++ oop
Friend function and friend classes in c++ oop
Private and protected data of a class can be accessed by making a function as a friend function of the class.
Example of Friend function of two different classes in c++ oop
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 28 29 30 31 |
#include <iostream> using namespace std; class two; class one { private: int n1=1; public: friend int add(one, two); }; class two { private: int n2=6; public: friend int add(one
, two); }; int main() { one object1; two object2; cout<<"Sum: "<< add(object1, object2); return 0; } int add(one object1, two object2) { return (object1.n1 + object2.n2); } |