FRIEND CLASS IN C++ With Example - DEEP CODER

Breaking

printf("Learn Deep Coding Here!!");

FRIEND CLASS IN C++ With Example

Definition of Friend Class

Similar to friend function we can make one class to be a friend of another class which is referred to as friend class. So that the friend class can gain access to private members defined within the other class. It’s important to remember that friend class can only access the names defined within the other class instead of inheriting other class. Precisely, the members of the first class cannot become the members of the friend class. These friend classes are rarely used.
The friend class can be declared in more than a single class. It is considered as a short alternative method for friend function because with the help of this we can create a friend class which can access the whole data members and function instead of creating multiple friend functions.
  1. #include <iostream>
  2. using namespace std;
  3. class First
  4. {
  5. // Declare a friend class
  6. friend class Second;
  7. public:
  8. First() : a(0){}
  9. void print()
  10. {
  11. cout << "The result is "<< a << endl;
  12. }
  13. private:
  14. int a;
  15. };
  16. class Second
  17. {
  18. public:
  19. void change( First& yclass, int x )
  20. {
  21. yclass.a = x;
  22. }
  23. };
  24. int main()
  25. {
  26. First obj1;
  27. Second obj2;
  28. obj1.print();
  29. obj2.change( obj1, 5 );
  30. obj1.print();|
  31. }
  32. //Output
  33. The result is 0
  34. The result is 5

No comments:

Post a Comment