Friends Of Classes

From RAD Studio
Jump to: navigation, search

Go Up to Classes Index

A friend F of a class X is a function or class, although not a member function of X, with full access rights to the private and protected members of X. In all other respects, F is a normal function with respect to scope, declarations, and definitions.

Since F is not a member of X, it is not in the scope of X, and it cannot be called with the x.F and xptr->F selector operators (where x is an X object and xptr is a pointer to an X object).

If the specifier friend is used with a function declaration or definition within the class X, it becomes a friend of X.

friend functions defined within a class obey the same inline rules as member functions (see Inline functions). friend functions are not affected by their position within the class or by any access specifiers. For example:

class X {
   int i;                           // private to X
   friend void friend_func(X*, int);
/* friend_func is not private, even though it's declared in the private section */
public:
     void member_func(int);
};
/* definitions; note both functions access private int i */
void friend_func(X* xptr, int a) { xptr->i = a; }
void X::member_func(int a) { i = a; }
X xobj;
/* note difference in function calls */
friend_func(&xobj, 6);
xobj.member_func(6);

You can make all the functions of class Y into friends of class X with a single declaration:

class Y;                      // incomplete declaration
class X {
   friend Y;
   int i;
   void member_funcX();
};
class Y; {                    // complete the declaration
   void friend_X1(X&);
   void friend_X2(X*);
.
.
.
};

The functions declared in Y are friends of X, although they have no friend specifiers. They can access the private members of X, such as i and member_funcX.

It is also possible for an individual member function of class X to be a friend of class Y:

class X {
.
.
.
   void member_funcX();
}
class Y {
   int i;
   friend void X::member_funcX();
.
.
.
};

Class friendship is not transitive: X friend of Y and Y friend of Z does not imply X friend of Z. Friendship is not inherited.

See Also