Cpp Friend Functions
# C++ Friend Functions
[ C++ Classes & Objects](#)
A friend function of a class is defined outside the class's scope but has access to all of the class's private (private) and protected (protected) members. Although the friend function's prototype 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 **friend** before the function's prototype in the class definition, 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
#includeusing 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; }// 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 that class */cout<<"Width of box : "<<box.width<<endl; }// Main function of the program int main(){Box box; // Use member function to set width box.setWidth(10.0); // Use friend function to print width printWidth(box); r
YouTip