Friend function

A friend function is a function that is not a member of a class but has access to the class's private and protected members.

Sample program:

#include <iostream>

class Rectangle
{
   double width;
   public:
   friend void printWidth( Rectangle rectangle );
   void setWidth( double wid );
};

// Member function definition
void Rectangle::setWidth( double wid )
{
    width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Rectangle rectangle )
{
   /* Because setWidth() is a friend of Rectangle, it can
    directly access any member of this class */
   cout << "Width of Rectangle : " << rectangle.width <<endl;
}

// Main function for the program
int main( )
{
   Rectangle rectangle;

   // set Rectangle width without member function
   rectangle.setWidth(10.0);
  
   // Use friend function to print the width.
   printWidth( rectangle );

   return 0;
}
When the above code is compiled and executed, it produces following result:
Width of Rectangle : 10

No comments:

Post a Comment