Friend classes in C++ give us access to non-member functions or other classes. In this article Kais shows us exactly how and why we should use friend classes and functions.
C++ Tricks of the Trade: Friend Functions - Friend Classes (Page 4 of 5 )
As well as choosing a non-member friend function, a class has two other possibilities for its friends. A class can declare a member function of another class as a friend, or declare another class as a friend class.
Friend classes are used in cases where one class is tightly coupled to another class. For example, suppose we have a class CPoint that represents a coordinate, and a class CPointCollection that holds a list of points. Since the collection class may need to manipulate point objects, we could declare CPointCollection as a friend of the CPoint class:
// Forward declaration of friend class. class CPointCollection;
// Point class. class CPoint { friend CPointCollection;
Since the collection class is a friend of CPoint, it has access to the internal data of any point object. This is useful when individual elements of the collection need to be manipulated. For example, a set method of the CPointCollection class could set all CPoint elements to a particular value:
class CPointCollection { public: CPointCollection(const int nSize) : m_vecPoints(nSize) {
The set member can iterate over the collection and reset each point:
void CPointCollection::set(const double x, const double y) { // Get the number of elements in the collection. const int nElements = m_vecPoints.size();
// Set each element. for(int i=0; i<nElements; i++) { m_vecPoints[i].m_x = x; m_vecPoints[i].m_y = y; } }
One thing worth noting about friend classes is that friendship is not mutual: although CPointCollection can access CPoint, the converse is not true. Friendship is also not something that is passed down a class hierarchy. Derived classes of CPointCollection will not be able to access CPoint. The principle behind this is that friendship is not implicitly granted; each class must explicitly choose its friends.