Table of Contents

1. Public, private, and friends

Remember that when member variables and functions of a class are set to public they can be accessed by anything and when they are set to private these members can only be accessed from within the class itself.

We can make an exception to this rule by declaring some external function or other class as a friend of the class we're creating. A friend function or class has access to any private or protected members of the class.

2. Friend function

The friend function will be declared within the class' declaration:

class MyClass
{
  public:
  void Hi();

  private:
  int name;

  friend void PrintMyClass( const MyClass& item );
};

And then it can be defined in a source (.cpp) file elseware:

void PrintMyClass( const MyClass& item )
{
  // name is private, but this function can access it.
  cout << item.name << endl;
}

3. Friend class

A friend class is the same sort of thing except that any member function of our friend class has access to any private members of the other class.

class ClassWithAFriend
{
  private:
  int name;

  friend class FriendlyClass;
};

That other class would be declared elseware, and any functions it has can access our ClassWithAFriend's members.

class FriendlyClass
{
public:
    void Display( const ClassWithAFriend& myFriend )
    {
        cout << myFriend.name << endl;
    }
};

However - it doesn't go both ways.

Keep in mind that if classA declares that classB is its friend, this means that classB has access to classA's members. However, this does not mean that classA has access to classB's members - we would have to explicitly state "classA is a friend" within the classB class.

4. Application of friends

Usually the best design is to keep member variables private - no exceptions. By exposing member data externally, that means the data can be accessed or changed without error checks, and updates in the codebase will be more difficult.

I tend to ONLY use the friend feature for one of two things:

  1. A tester class that contains unit tests for a given class; the tester will have access to the private member variables to confirm that proper changes are made after a function call.
  2. A manager class that handles the class it is a friend of, so it can manage everything about that class. However, design-wise, a manager class can still be designed without "friend" status just fine using the class' Get and Set functions.

Author: RachelWil

Created: 2026-10-14 Wed 11:12

Validate