Friend Classes

C++ Specific —>

A friend class is a class all of whose member functions are friend functions of a class, that is, whose member functions have access to the other class's private and protected members.

Example

// Example of the friend class
class YourClass
{
friend class YourOtherClass;  // Declare a friend class
private:
   int topSecret;
};

class YourOtherClass
{
public:
   void change( YourClass yc );
};

void YourOtherClass::change( YourClass yc )
{
   yc.topSecret++;    // Can access private data
}

Friendship is not mutual unless explicitly specified as such. In the above example, member functions of YourClass cannot access the private members of YourOtherClass.

Friendship is not inherited, meaning that classes derived from YourOtherClass cannot access YourClass's private members; nor is it transitive, so classes that are friends of YourOtherClass cannot access YourClass's private members.

END C++ Specific