Sunday, June 2, 2019

Friend Function and Friend class


Friend Function:

It’s a kind of non member function.
->But can access the private member of class.

#include<iostream.h>
#include<conio.h>
class  student
{
          private:
                   int y;
                   friend void display(student x)
};
void display(student x)
{
          x.y=949;
          cout<<x.y;
}
void main()
{
          clascr();
          student  z;
          display(z);
          getch();
}
E.g.:
#include<iostream.h>
#include<conio.h>
class  a;
{
          private:
                   int x;
                   friend void display(a  t);
};
void display(a  t)
{
          t.x=999;
          cout<<t.x;
}
void main()
{
          clrscr();
          a  z;
          display(z)
          getch();
}
Another example of two class:
#include<iostream.h>
#include<conio.h>
class  a;
class  b
{
          private:
                   int x;
          public:
                   friend void display(a t,b y)
};
class  b
{
          private:
                   int z;
          public:
                   friend void display(a t,b y)
};
void display(a t,b y)
{
          t.x=999;
          y.z=767;
          cout<<t.x<<” ”<<y.z;
}
void main()
{
          clrscr();
          a  z;
          b  p;
          display(z,p);
          getch();
}


Friend class:

We can declare friend class, when we declare the friend class , all the member of that become friend function ,that can access the private and protected member of class.

e.g.:

#include<iostream.h>
#include<conio.h>
class  b;
class a;
{
          private:
                   int  x;
          public:
                   friend class b;
}
class  b
{
          public:
                   void display(a t)
                   {
                             t.x=999;
                             cout<<t.x;
                   }
};
void main()
{
          clrscr();
          a  z;
          b  p;
          p.display(z);
          getch();
}

No comments:

Post a Comment