i2tutorials

CPP -Friend Functions

Friend Functions

 

A class friend function is defined beyond the scope of that class, but it has the right to access all private and protected members of the class. Even though friend function prototypes are shown in the class definition, friends are not member functions. 

 

To declare a function as a friend of a class, precede the prototype of the function within the class definition with the keyword friend as follows:

#include <iostream>
using namespace std;
class Box
{
 double width;
 public:
 friend void printWidth( Box box );
 void setWidth( double wid )
 { width = wid; 
 }
};
void printWidth( Box box )
{
 cout << "Width of box : " << box.width <<endl;
}
int main( )
{ 
Box box;
box.setWidth(10.0);
printWidth( box );
return 0;
}

Output:

Exit mobile version