AutosarC++18_10-A11.3.1

Friend declarations shall not be used

Required inputs: IR

Rationale

Friend declarations reduce encapsulation and result in code that is more difficult to maintain.

Exceptions

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 byexception
         {
              // 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.

Possible Messages

Key

Text

Severity

Disabled

friend_class

Do not use friend type declarations.

None

False

friend_decl

Do not use friend declarations.

None

False

Options

allow_comparison_operators

allow_comparison_operators : bool = True

Whether declaring comparison operators as friend functions should be allowed.