Friend Class in C++

Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class

  •       A friend class can have access to the data members and functions of another class in which it is declared as a friend.

Syntax of friend class:

Class M;

Class H{

 Friend class M;

};

class M{

  //body of class M

}

 

Example No.1: friend class:

#include<iostream>

using namespace std;

class A{

        int a;

    public:

          A(){

               a=2;

           }

           friend class B;

};

class B{

         int b;

   public:

          B(){

             b=7;

         }

         int add(){

                A obj;

                return obj.a+b;               

          }

         int sub(){

                 A obj;

                 return obj.a-b;               

}

};

int main(){

           B x;

           cout<<"The sum is:"<<x.add()<<endl;

           cout<<"The sub is:"<<x.sub();

         return 0;

}

 

Output:

Sum: 13

 

Example No.2:

#include<iostream>

using namespace std;

class Rectangular{

           float l;

           float w;

           friend class area;   // friend class declaration

           public:

           void set();       //function declaration

                         

};

void Rectangular::set()

    {

           l=70;

           w=80;

    }

class area{

                int s;

           public:

               area(){

                             s=12;

               }

                void display(Rectangular  r){

                          cout<<"The lenth is: "<<r.l<<endl;

                          cout<<"The width is: "<<r.w<<endl;

                          cout<<"The area is: "<<s<<endl;

              }

};

int main(){

           Rectangular x;

           x.set();

           area a;

           a.display(x); 

          return 0;

}

 

Output:

The lenth is: 70

The width is: 80

The area is: 12

 


Post a Comment

0 Comments

Close Menu