Share via


Class Member Functions and Classes as Friends

Class member functions can be declared as friends in other classes. Consider the following example:

class B;
class A
{
    int Func1( B& b ) ;
    int Func2( B& b ) ;
};

class B
{
private:
    int _b;
    friend int A::Func1( B& );   //  Grant friend access to one
                                //   function in class B.
};
 int A::Func1( B& b ) { return b._b; } //  OK: this is a friend.
 int A::Func2( B& b ) { return b._b; } //  Error: _b is a private member.

In the preceding example, only the function A::Func1( B& ) is granted friend access to class B. Therefore, access to the private member _b is correct in Func1 of class A but not in Func2.

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. Suppose the friend declaration in class B had been:

friend class A;

In that case, all member functions in class A would have been granted friend access to class B. The following code is an example of a friend class:

#include <iostream.h>

class YourClass
{
friend class YourOtherClass;  // Declare a friend class
public:
  YourClass() : topSecret(0){}
  void printMember() { cout << topSecret << endl; }
private:
   int topSecret;
};

class YourOtherClass
{
public:
   void change( YourClass& yc, int x ){yc.topSecret = x;}
};

void main() {
  YourClass yc1;
  YourOtherClass yoc1;
  yc1.printMember();
  yoc1.change( yc1, 5 );
  yc1.printMember();
}

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. Friendship is not transitive, so classes that are friends of YourOtherClass cannot access YourClass's private members.

Figure 10.2 shows four class declarations: Base, Derived, aFriend, and anotherFriend. Only class aFriend has direct access to the private members of Base (and to any members Base might have inherited).

Figure 10.2   Implications of friend Relationship