Section 2 - Friends

5A.2.1 Declaring Friend Functions

scenic bears

If you want to allow an ordinary C++ function to access private data of a class, you declare that function to be a friend of the class:

class B
{
  friend void normalFun();

private:
  int privateThing;
};

void normalFun()
{
  B b;
  b.privateThing = 2;
};

As you can see by looking at the way that normalFun() accesses the private member b, of class B, if that class had not declared normalFun to be friends, we would have gotten a compiler error.

5A.2.2 Declaring Friend Classes

The same thing we did for a function to allow it access to a class's private data, declaring it to be a friend, can be done for an entire separate class.  That is, if class B wants to allow class A access to all of its innermost secrets, then there would be a friend declaration in class B's prototype.

class A
{
  void memberFun(B b)
  { b.privateThing = 1; }
};

class B
{
  friend class A;

private:
  int privateThing;
};

By declaring class A to be a friend of class B, we are allowing all class and instance methods of A to mutate or access all private data of class B.