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
.
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
. 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).
Figure 10.2 Implications of friend Relationship