Pages

Monday, 8 November 2021

Friend function & Friend class in c++

A non-member function cannot have an access to the private data of a class, however there could be a situation where we would like a global function to access private data of one or more classes. To achieve this c++ provides a keyword called friend. 

friend function is a function that has access to the private members of a class but is not itself a member of that class. 

Syntax:

     friend returntype fun_name(args); 

Characteristics:

o  It is not in the scope of the class to which it has been declared as friend.

o  Since it is not in the class, it need not be called by using object of class.

o  It can be invoked like a normal function

o  Usually friend functions has objects as arguments

o  A function can be a friend of more than one class.

o  Private data is accessed using the dot operator

/* friend function  using single class*/

#include<iostream.h>
#include<conio.h>
class sample
{
 int a,b;
 friend void print(sample);
};
void print(sample s)
{
 s.a=10;
 s.b=20;
 cout<<"a="<<s.a;
 cout<<"b="<<s.b;
}
void main()
{
 clrscr();
 sample s;
 print(s);
getch();
}

/* friend function using two class*/

#include<iostream.h>
#include<conio.h>
class second; //forward declaration
class first
{
 int a;
 public:
 void geta()
 {
  cout<< "enter a value:";
  cin>>a;
 }
 friend void big(first ,second); //comparing 2 objects of class types.
};

class second
{
 int b;
 public:
 void getb()
 {
  cout<< "enter b value:";
  cin>>b;
 }
 friend void big(first ,second); //comparing 2 objects of class types.
};
void big( first f,second s)
{
 if(f.a>s.b)
 cout<< "a is big";
 else if(s.b>f.a)
 cout<< "b is big";
 else
 cout<< "both are equal";
}
void main()
{
 first f;
 second s;
 f.geta();
 s.getb();
 big(f,s);
 getch();
}

 

FRIEND CLASSES: 

If we make the entire class as a friend then automatically all the member functions of the class become friends.

Friendship is granted not taken i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend. 

/* friend classes */

#include<iostream.h>
#include<conio.h>
class sample2; //forward declaration
class sample1
{
int a,b;
public:
void samp1(int=5,int=6);
friend class sample2;
};
void sample1::samp1(int x,int y)
{
a=x;
b=y;
}
class sample2
{
public:
void fun3(sample1 &); //  argument as class sample1 and with
referece type
void fun4(sample1 &);
};
void sample2::fun3(sample1 &p)
{
cout<<p.a<<endl;
}
void sample2::fun4(sample1 &q)
{
cout<<q.b<<”\t”;
}
void main()
{
clrscr();
sample1 s1;
sample2 s2;
s1.samp1(8);
s2.fun3(s1);
s2.fun4(s1);
getch();
}
Output:
8    6
 

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...