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.
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( )
// set Rectangle width without member function
// Use friend function to print the width.
printWidth( rectangle );
When the above code is compiled and executed, it produces following result:
Width of Rectangle : 10