C++ Friend Functions
A friend function of a class is defined outside the class, but has the right to access all private and protected members of the class. Although the prototype of the friend function 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. 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 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, you need to place the following declaration in the definition of class ClassOne:
friend class ClassTwo;
Please look at the following program:
Example
When the above code is compiled and executed, it produces the following results:
Width of box : 10other extensions