Easy Tutorial
❮ Cpp References Unary Operators Overloading ❯

C++ Friend Functions

C++ Classes & Objects

A friend function of a class is defined outside that class's scope but has the right to access all private and protected members of the class. Although the prototype for the friend function appears in the class definition, the friend function is not a member function.

A friend can be a function, which is then called a friend function; a friend can also be a class, which is then called a friend class, in which case the entire class and all its members are friends.

To declare a function as a friend of a class, precede the function prototype in the class definition with the keyword 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;

Consider the following program:

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 this class */
   cout << "Width of box : " << box.width <&lt;endl;
}

// Main function for the program
int main( )
{
   Box box;

   // Use member function to set width
   box.setWidth(10.0);

   // Use friend function to print width
   printWidth( box );

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Width of box : 10

C++ Classes & Objects

❮ Cpp References Unary Operators Overloading ❯