What is friend function? Explain the characterstics with a suitable example.

We generally have a belief that a non-member function cannot access the private data member of the class. But this is made possible using a friend function. A friend function is that which does not belong to the class still have complete access to the private data members of the class. We simply need to declare  the function inside the class using the keyword ‘friend’. The syntax for declaring the friend function is as follows:
class demo {
Public:
friend void func (void);
}
The characteristics of friend function are as follows:

  • It can be declared both in the private and the public part of the class without altering the meaning
  • It is not called using the object of the class.
  • To access the data members of the class, it needs to use the object name, the dot operator and the data member’s name. Eg: obje.xyz
  • It is invoked like a normal function
  • It does not belong to the class

Example:
include <iostream.h>
using namespace std;
class one;
class two {
int a;
public:
void setvalue (int a ) {a=n;}
friend void max (two, one);
};
class one {
int b;
public:
void setvalue (int n) {b=n;}
friend void max (two, one);
};
void max (two s, one t){
if (s.a>=t.b)
cout<<s.a;
else
cout<<t.b;
}
int main (){
one obj1;
obj1.setvalue(5);
two obj2;
obj2.setvalue(10);
max(obj2,obj1);
return 0;
}

Leave a Reply

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