Share via


Friend Functions

C++ Specific —>

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.

A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

Example 1

A friend function is defined as a nonmember function:

class Complex
{
public:
   Complex( float re, float im );
   friend Complex operator+( Complex first, Complex second );
private:
   float real, imag;
};

Example 2

Complex operator+( Complex first, Complex second )
{
   return Complex( first.real + second.real,
                   first.imag + second.imag );
}

In this example, the friend function operator+ has access to the private data members of the Complex objects it receives as parameters.

Notice that the friend keyword does not appear in the function definition.

END C++ Specific