A friend class is a class that can access private and protected members of another class.

Let’s take an example of Line and Point class. A line is created from two end points, so Line contains two end points.

 
#include <iostream>
#include <cmath>
 
class Point
{
    int m_x{};
    int m_y{};
 
public:
    Point() = default;
    Point(int x, int y)
        : m_x{x}, m_y{y}
    {
    }
 
    friend class Line;
};
 
class Line
{
    Point m_start{};
    Point m_end{};
public:
    Line() = default;
    Line(int x1, int y1, int x2, int y2)
        : m_start{Point{x1, y1}}, m_end{Point{x2, y2}}
    {
    }
 
    double length() const
    {
        double dx = m_start.m_x - m_end.m_x;
        double dy = m_start.m_y - m_end.m_y;
        return std::sqrt(dx * dx + dy * dy);
    }
};
 
int main(int argc, char const *argv[])
{
    Line l{1, 2, 3, 4};
    std::cout << l.length();
    return 0;
}

Line class contains a member function length which access private members of two end points. Because Point has class Line as friend, Line can access private members of Point.

Declaring Line as friend of Point using friend class Line;, we do not require to forward declare Line but this same line serves as forward declaration.

Few things to note about class friends:

  1. The friendship is not reciprocal. It means Line is friend of Point that does not mean Point is friend of Line.
  2. Friendship is not transitive. For example, if A is friend of B and B is friend of C then it does not mean A is friend of C.
  3. Friendship is not inherited. For example, if B is a friend of A, classes derived from B are not friend of A.

References

  1. https://www.learncpp.com/cpp-tutorial/friend-classes-and-friend-member-functions/