Rule A11-3-1 (required, implementation, automated)
Friend declarations shall not be used.
Rationale
Friend declarations reduce encapsulation and result in code that is more difficult to maintain.
Exception
It is allowed to declare comparison operators as friend functions, see A13-5-5.
Example
// $Id: A11-3-1.cpp 325916 2018-07-13 12:26:22Z christof.meerwald $
class A
{
public:
A& operator+=(A const& oth);
friend A const operator+(A const& lhs, A const& rhs); // Non-compliant
};
class B
{
public:
B& operator+=(B const& oth);
friend bool operator ==(B const& lhs, B const& rhs) // Compliant by exception
{
// Implementation
}
};
B const operator+(B const& lhs, B const& rhs) // Compliant
{
// Implementation
}
See also
JSF December 2005 [8]: AV Rule 70 A class will have friends only when a function or object requires access to the private elements of the class, but is unable to be a member of the class for logical or efficiency reasons. HIC++ v4.0 [9]: 11.2.1 Do not use friend declarations.