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. #include <iostream>
2. using namespace std;
3. class B; // forward declaration
4. class A {
5. private:
6. int data;
7. public:
8. A(): data(12){ }
9. friend int func(A , B); //friend function Declaration
10. };
11. class B {
12. private:
13. int data;
14. public:
15. B(): data(1){ }
16. friend int func(A , B); //friend function Declaration
17. };
18. int func(A d1,B d2)
19. /*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.*/
20. {
21. return (d1.data+d2.data);
22. }
23. int main()
24. {
25. A a;
26. B b;
27. cout<<"Data: "<<func(a,b);
28. return 0;
29. }
Here, we do sum of two different class private data member using friend class.
A friend function in C++ is a function which you can use to view and manipulate a class definition and an object with private permissions. A friend function prototype is declared into the class definition.
TCCI Computer coaching teach Object Oriented Programming Language like c++, Java , Python etc in Bopal and satellite in Ahmedabad.
For more information about TCCI
Call us @ 9825618292
Visit us @ http://tccicomputercoaching.com/workshop/
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. #include <iostream>
2. using namespace std;
3. class B; // forward declaration
4. class A {
5. private:
6. int data;
7. public:
8. A(): data(12){ }
9. friend int func(A , B); //friend function Declaration
10. };
11. class B {
12. private:
13. int data;
14. public:
15. B(): data(1){ }
16. friend int func(A , B); //friend function Declaration
17. };
18. int func(A d1,B d2)
19. /*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.*/
20. {
21. return (d1.data+d2.data);
22. }
23. int main()
24. {
25. A a;
26. B b;
27. cout<<"Data: "<<func(a,b);
28. return 0;
29. }
Here, we do sum of two different class private data member using friend class.
A friend function in C++ is a function which you can use to view and manipulate a class definition and an object with private permissions. A friend function prototype is declared into the class definition.
TCCI Computer coaching teach Object Oriented Programming Language like c++, Java , Python etc in Bopal and satellite in Ahmedabad.
For more information about TCCI
Call us @ 9825618292
Visit us @ http://tccicomputercoaching.com/workshop/
No comments:
Post a Comment