What are friend functions? Explain there characteristics with a suitable example.

We generally have a belief in object oriented programming that a non member function of any class cannot be access the private data members or member functions. But this is made possible using a friend function. A friend function is that which does not belong to the class still has 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 A
{
public:
friend void demo();
};

The characteristics of a friend function are as follows:
1. Friend functions can be declared both in the private and the public part of the class.
2. Friend functions is not called using the object of the class.
3. Friend functions access the data members of the class, it needs to use the object name, the dot operator and the data member’s name. 
4. Friend functions is invoked like a normal function.
5. Friend functions does not belong to the class member.

An example program is as follows with program code:


#include<iostream>
using namespace std;
class A;
class B
{
int b;
public:
void setdata(int n)
{
b=n;
}
friend void max(B,A);
};

class A
{
int a;
public:
void setdata(int n)
{
a=n;
}
friend void max(B,A);
};

void max(B x, A y)
{
if(x.b >= y.a)
{
cout<<"Maximum element is : "<<x.b;
}
else
{
cout<<"Minimum element is :"<<y.a;
}
}
int main()
{
A obja;
obja.setdata(5);
B objb;
objb.setdata(10);
max(objb, obja);
return 0;
}



The program output is tested on www.jdoodle.com
Output:
Maximum element is : 10

Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: