C++ Friend function
A function is defined as a friend function in C++, then the
protected and private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a
friend function.
For accessing the data, the declaration of a friend function
should be done inside the body of a class starting with the keyword friend.
Syntax:
class MCA
{
private:
data member;
public :
friend return type functionname(argument list)
};
Program:
#include<iostream.h>
#include<conio.h>
class MCA;
class mca
{
int a,b;
public:
void getvalue()
{
a=20;
b=30;
}
friend void sum(MCA,
mca);
};
class MCA
{
int x,y;
public:
void getvalue()
{
x=50;
y=70;
}
friend voidsum(MCA,mca);
};
void sum(MCA u,mca v)
{
int m,n;
m=v.a+u.x;
n=v.b+u.y;
cout<<m<<n;
}
void main()
{
MCA a1;
mca a2;
a1.getvalue();
cout<<”class mca
call”;
a2.getvalue();
sum(a1,a2);
getch();
}
Output:
Call mca call 70 100
No comments:
Post a Comment