What is friend function and how we use it in classes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is friend function and how we use it in classes?

too much confused about it

9th Nov 2016, 2:32 PM
Mehran Waheed
Mehran Waheed - avatar
4 Answers
+ 2
friend is a keyword in c++. If you use on any function or class in other class(let say s class). the function or class with friend keyword can access all member function including private member of class s1.
9th Nov 2016, 2:50 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 2
#include <iostream> using namespace std; class MyClass { public: int hr; private: int regVar; friend void someFunc(MyClass &obj); }; void someFunc(MyClass &obj) { obj.regVar = 42; cout << obj.regVar; } //above you can see someFunc use private member //of class Myclass that is regVar int main() { MyClass obj; someFunc(obj); } I have use tutorial example.
9th Nov 2016, 3:00 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
any example?
9th Nov 2016, 2:55 PM
Mehran Waheed
Mehran Waheed - avatar
0
thanku very much
9th Nov 2016, 3:05 PM
Mehran Waheed
Mehran Waheed - avatar