c++

A friend function is the type of function in c++ that defines inside the class as a friend of that class but it never be a member function of that class though it can access all the primitive and private data of a class. Let’s see an example program of friend function.

a simple friend function program

include 
 using namespace std;
 class friends
 {
     private:
         int a=4,b=8;
     public:
         void add(){cout<<"Add : "<<a+b;}
         //friend function
         friend int mul(friends);
 };
 // friend function definition
 int mul(friends D)
 {
     //accessing private data from non-member function
     int m,n;
     m=D.a;
     n=D.b;
     return m*n;
 }
 int main()
 {
     friends D;
     D.add();
     cout<<"\nmul: "<< mul(D);
     return 0;
 }

Leave a Reply

Your email address will not be published. Required fields are marked *