/    /  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:

  • A friend function does not belong in the class in which it was declared a friend.
  • It may not be invoked using the object of this class.
  • One can invoke it as a normal function without any object.
  • In contrast to member functions, it cannot use member names directly.
  • It can be declared publicly or privately without altering its meaning.
  • Usually, objects are used as arguments.