Class Member Functions and Classes as Friends

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

class A

{

private:

int _a;

friend int B::Func1( A ); // Grant friend access to one

// function in class B.

};

class B

{

public:

int Func1( A a ) { return a._a; } // OK: this is a friend.

int Func2( A a ) { return a._a; } // Error: _a is a private

// member.

};

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

Suppose the friend declaration in class A had been:

friend class B;

In that case, all member functions in class B would have been granted friend access to class A. Note that “friendship” cannot be inherited, nor is there any “friend of a friend” access. 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).