What is friend function in OOP? tccicomputercoaching.com

Page 1

What is friend function in OOP? tccicomputercoaching.com A friend function in OOP is a function declared as friend of a class‌ which means that this class in question can access the private or protected data of this other class. Actually, private or protected data of one class can't accessible by another class. But friend class makes this possible.

Let us understand one example: 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.

#include <iostream> using namespace std; class B; // forward declaration class A { private: int data; public: A(): data(12){ } friend int func(A , B); //friend function Declaration }; class B { private: int data; public: B(): data(1){ } friend int func(A , B); //friend function Declaration }; int func(A d1,B d2) /*Function func() is the friend function of both classes A and B. So, the private data of both class can be accessed from this function.*/ { return (d1.data+d2.data); } int main() { A a; B b;


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.