50 likes | 181 Vues
In C++, a class can declare another class as a "friend," allowing the friend class to access its private and protected members. This relationship enables seamless interaction between classes by granting friend functions the ability to manipulate the data of the owning class. When a class is made a friend, all its member functions are treated as friend functions as well, thus ensuring that they have access to the private data of the other class. This article explores the concept of friend classes with examples to help illustrate their usage and benefits in object-oriented programming.
E N D
Friend Class Like friend function a class can also be declared as friend of other class. When a class is created as friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration). Similarly like, friend function. A class can be made a friend of another class using keyword friend.
Friend Class For example: class A { friend class B; // class B is a friend class ..... ..... ..... }; class B{ ..... ..... ..... }; When a class is made as friend class, all the member functions of that class becomes friend function. In this program, all member functions of class B will be friend function of class A. Thus, any member function of class B can access the private and protected data of class A.
Friend Class If B is declared friend class of A then, all member functions of class B can access private data and protected data of class A.
Friend Class class A { int a; public: friend class B; void changea() {a=10;cout<<"value in A"<<a;} }; class B { public: void changeb(A x) {x.a=100;cout<<"\nValue in B"<<x.a;} }; void main() { A obj1; obj1.changea(); B obj2; obj2.changeb(obj1); }