In this guide we will see the concept of friend class, it's usage and program in C++.
A friend class is a class that accesses the private and protected members of another class which is declared as friend. It is beneficial if a user wants to access a private class of another class. We use the keyword friend to declare friend class.
class X{ private: //..... protected: //..... function() { //Statements } friend class Y; }; class Y{ private: .... public: function(X ob) { //Statements } };
1. We can access private and protected members of other classes.
2. Enables classes to share private members' information.
3. Beneficial if classes have the same type of data members.
#include using namespace std; class St1{ public: int rollno,marks; void gdetail() { cout<<"Enter roll no. "; cin>>rollno; cout<<"Enter Marks "; cin>>marks; } friend class St2; }; class St2{ public: int r,m,avg; void data() { cout<<"\nEnter roll no. "; cin>>r; cout<<"Enter marks "; cin>>m; } void average(St1 ob) { avg=(ob.marks+m)/2; cout<<"\nThe average marks= "<<avg; } }; int main() { St1 x; St2 y; x.gdetail(); y.data(); y.average(x); }
Submitted by Akansh Upadhyay (akansh)
Download packets of source code on Coders Packet
Comments