How to access the C++ friend class?
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 |
//C++ Friend class by T4Tutorials #include <iostream> using namespace std; class T4 { private: char ch='G'; int num = 9; public: friend class Tutorials; }; class Tutorials { public: void disp(T4 obj2){ cout<<obj2.ch<<endl; cout<<obj2.num<<endl; } }; int main() { Tutorials obj1; T4 obj2; obj1.disp(obj2); return 0; } |
Output
G
9
Friend Function in C++
If we declare a function as a friend in a class, then this function can access the private and protected members of that class. You must know that a global function can also be declared as a friend function of the class.
Syntax of friend function in C++
class class_name_T4Tutorials { … friend return_type function_name(arguments); … }Now, you can define the friend function as a normal function to access the data of the class. No friend keyword is used in the definition.
class class_name { … friend return_type function_Name(argument/s); … } return_type function_Name(arguments) { … // Private and protected data of class can be accessed from this function // because it is a friend function of class. … }
How to access the C++ friend function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> using namespace std; class T4Tutorials { private: char ch='G'; int num=9; public: friend void disp(T4Tutorials obj); }; void disp(T4Tutorials obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; } int main() { T4Tutorials obj; disp(obj); return 0; } |
Output
G
9
How to find factorial using friend function in C++?
Factorial using friend function in C++
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 32 |
#include<iostream> using namespace std; class T4Tutorials { private: int n; public: void input() { cout << "Please Enter a Number :"; cin >> n; } friend void factorial(T4Tutorials t); }; void factorial(T4Tutorials t) { int f = 1, i; for (i = 1; i <= t.n; i++) { f = f*i; } cout << "\nThe factorial is :" << f; } int main() { T4Tutorials t; t.input(); factorial(t); return 0; } |