Share via


Class Member Functions and Classes as Friends

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

// classes_as_friends1.cpp
// compile with: /c
class B;

class A {
public:
   int Func1( B& b );

private:
   int Func2( B& b );
};

class B {
private:
   int _b;

   // A::Func1 is a friend function to class B
   // so A::Func1 has access to all members of B
   friend int A::Func1( B& );
};

int A::Func1( B& b ) { return b._b; }   // OK
int A::Func2( B& b ) { return b._b; }   // C2248

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:

// classes_as_friends2.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
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;}
};

int 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.

A managed type cannot have any friend functions, friend classes, or friend interfaces.

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.

The following figure 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).

Implications of friend Relationship

Implications of friend relationship

See Also

Reference

friend (C++)