0% found this document useful (0 votes)
202 views

Friend Function in C Plus Plus

C++ allows the declaration of friend functions and friend classes to access private and protected members of a class. A friend function is defined outside the class but has access to private and protected members, even though it is not a member function itself. To declare a function as a friend, the friend keyword is used along with the function prototype in the class definition. The document provides two examples of friend functions - one that calculates the sum of private members, and another that returns the maximum of two private members.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views

Friend Function in C Plus Plus

C++ allows the declaration of friend functions and friend classes to access private and protected members of a class. A friend function is defined outside the class but has access to private and protected members, even though it is not a member function itself. To declare a function as a friend, the friend keyword is used along with the function prototype in the class definition. The document provides two examples of friend functions - one that calculates the sum of private members, and another that returns the maximum of two private members.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

There is mechanism built in C++ programming to access private or protected data from

non-member function which is friend function and friend class.


A friend function of a class is defined outside that class' scope but it has the right to access
all private and protected members of the class. Even though the prototypes for friend
functions appear in the class definition, friends are not member functions.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:

FRIEND FUNCTION
#include<iostream.h>
#include<conio.h>
class sum
{
inta,b;
public:
voidget_ab()
{
cout<<"enter the values of a and b:";
cin>>a>>b;
}
friend void add(sum s);
};
void add(sum s)
{
cout<<"\n sum of a and b is:"<<s.a+s.b;
}
void main()
{
clrscr();
sum s1;
s1.get_ab();
add(s1);
getch();
}
FRIEND FUNCTION

#include<iostream.h>
#include<conio.h>
class testing
{
inta,b;
public:
voidget_ab()
{
cout<<"enter values of a and b:";
cin>>a>>b;
}
friendint max(testing t1);
};
int max(testing t1)
{
if(t1.a>t1.b)
{
return t1.a;
}
else
{
return t1.b;
}
}
void main()
{
clrscr();
testingobj;
obj.get_ab();
cout<<"MAXIMUM VALUE IS:"<<max(obj);
getch();
}

You might also like