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.
- #include <iostream>
- using namespace std;
- class First
- {
- // Declare a friend class
- friend class Second;
- public:
- First() : a(0){}
- void print()
- {
- cout << "The result is "<< a << endl;
- }
- private:
- int a;
- };
- class Second
- {
- public:
- void change( First& yclass, int x )
- {
- yclass.a = x;
- }
- };
- int main()
- {
- First obj1;
- Second obj2;
- obj1.print();
- obj2.change( obj1, 5 );
- obj1.print();|
- }
- //Output
- The result is 0
- The result is 5
No comments:
Post a Comment