C++ Friend Functions
A friend function of a class is defined outside the class but has access to all private and protected members of the class. Although the friend function's prototype appears in the class definition, the friend function is not a member function.
A friend can be a function, which is called a friend function; a friend can also be a class, which is called a friend class, and in this case the entire class and all its members are friends.
To declare a function as a friend of a class, you need to use the keyword before the function's prototype in the class definition friend, as shown below:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place the following declaration in the definition of class ClassOne:
friend class ClassTwo;
Please see the program below:
Example
#include
<
iostream
using
namespace
std;
class
Box
{
double
width
;
public
:
friend
void
printWidth
(
Box
box
)
;
void
setWidth
(
double
wid
)
;
}
;
// Member function definition
void
Box
::
setWidth
(
double
wid
)
{
width
=
wid
;
}
// Note: printWidth() is not a member function of any class
void
printWidth
(
Box
box
)
{
/*
Because printWidth() is a friend of Box, it can directly access any member of that class
*/
cout
<<
"
Width of box :
"
<<
box
.
width
<<
endl
;
}
// main function of the program
int
main
(
)
{
Box
box
;
// Set width using a member function
box
.
setWidth
(
10
.0
)
;
// Output width using the friend function
printWidth
(
box
)
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Width of box : 10
C++ Classes & Objects