Friend Functions
Friend Functions
Syntax:
friend
ReturnType
FunctionName
(
P
arameters
);
Purpose:
friend function is used when a non-member function needs access to the
A
private or protected members of a class.
Properties:
Friend functions are not members of the class.
They are declared inside the class but defined outside the class.
friend function has access to all members (private, protected, public) of
A
the class.
complex
c3
=
sumComplex
(
c1
,
c2
);
This function is invoked directly without using any object , e.g
c3.
sumComplex
(
c
1
,
c2
)// wrong
Can’t Access
datamembersdirectly. Requires an objectand
access them by
objectname
.
datamember
Limitations:
• riend functions break the encapsulation principle by allowing
F
external functions to access private members.
Code:
#include
<iostream>
using
namespace
std
;
class
complex
{
private:
int
real
;
int
imag
;
public:
complex
() {} // Default Constructor
complex
(
int
real,
int
imag)
{
this
->
real
=
real;
this
->
imag
=
imag;
}
void
display
()
{
cout<<real<<
" + "
<<imag<<
"i "
<<endl
;
}
friend
complex
sumComplex
(
complex
o1,
complex
o2);
};
complex
sumComplex
(
complex
o1,
complex
o2)
{
complex
temp
;
temp
.
real
=
o1
.
real
+
o2
.
real
;
temp
.
imag
=
o1
.
imag
+
o2
.
imag
;
return
temp
;
}
int
main
()
{
complex
c1
(
3
,
4);
c1
.
display
();
complex
c2
(
1
,
2
)
;
c2
.
display
();
complex
c3
=
sumComplex
(
c1
,
c
2
);
cout<<
"The sum of Complex numbers is = "
;
c3
.
display
();
return
0
;
}