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:
- The friendship is not reciprocal. It means
Lineis friend ofPointthat does not meanPointis friend ofLine. - Friendship is not transitive. For example, if
Ais friend ofBandBis friend ofCthen it does not meanAis friend ofC. - Friendship is not inherited. For example, if
Bis a friend ofA, classes derived fromBare not friend ofA.