C++ Friend Functions

C++ Classes & Objects

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

#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; } // Please 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 the class*/ cout << "Width of box : " << box.width <<endl; } // The main function of the program int main( ) { Box box; // Set width using a member function box.setWidth(10.0); // Use the friend function to output the width printWidth( box ); return 0; }

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

Width of box : 10

C++ Classes & Objects

other extensions