Friend Function Program in C Plus Plus
The
friend Function is such a type of
function which is not the part of any class but it can access the public,
protected and private data of the classes of which it is friend.
We
use only the friend keyword before the function to which we are willing to make
friend. Secondly all the classes which are friends of this function must be
declared before the first friend class definition.
Scenario
We
will declare
the two classes A and B and make a friend function show() preceding with
keyword friend. This function will access the data of both classes and perform
calculation on data and give the output to user.
So
Let’s start our work.
Program in
C++ of Friend Function
Code
#include<iostream>
using
namespace std;
class
B;
class
A{
private:
int a;
public:
A()
{
a=10;
}
friend void show(A,B);
};
class
B{
private:
int b;
public:
B()
{
b=10;
}
friend void show(A,B);
};
void
show(A x,B y)
{
int
c=x.a+y.b;
cout<<"C
======= "<<c<<endl;
}
int main()
{
A
a;
B
b;
show(a,b);
}
Program in
C++ of Friend Function
Output
Below
is the .exe file run of the above code on Dev C++ IDE.
As
you can see that we have successfully add the data of both classes in a friend
function and display the result in another variable.
That’s
it.
@@@
@@@ @@@ @@@ Thanks @@@ @@@ @@@ for @@ @@ visiting @@ @@
Post a Comment
Feel Free to Comment Us