C++ Concept Map

Friend

Classes can also control access to their private members by using the friend declaration. There are two variations on this:

  1. Access can be granted to individual member functions of another class by using the following form:
       friend return type X::f(param types...);
    
    any number of functions can be granted access in this manner.
  2. Access can be granted to all the functions of a class by:
       friend class X;
    

The best way to think about friend functions is that although they are actually declared in another scope, the friend declaration "imports" them into the scope of the declaration, thus allowing direct access to private members.

Of course, since friend functions are not member functions access still has to be through an object of the class declaring the friend.

For example, the function FR in class B, below is granted access to the private member x of class A, but still has to use an object of type A to effect the access:

class A {
private:
  int x;
...
friend void B::FR();
};

class B {
...
   void FR() {
      A a;
      cout << a.x; // direct access allowed by friend declaration
   }
...
};


Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley