Main Content

AUTOSAR C++14 Rule A11-3-1

Friend declarations shall not be used

Description

Rule Definition

Friend declarations shall not be used.

Rationale

You declare a function as friend of a class to access private members of the class outside the class scope.

class A
{
  int data;
  public:
    // operator+ can access private members of class A such as data
    friend A const operator+(A const& lhs, A const& rhs);
};
Friend functions and friend classes reduce data encapsulation. Private members of a class are no longer accessible only through the class methods.

Code with friend functions can be difficult to maintain. For instance, if class myClass has a friend class anotherClass, when you change a data member of myClass, you have to find all instances of its usage in member functions of anotherClass.

Polyspace Implementation

The rule checker flags all uses of the friend keyword.

The checker follows specifications of AUTOSAR C++ 14 release 18-03 (March 2018). However, release 18-10 and later releases of AUTOSAR C++14 allows an exception for comparison operators such as operator==. If the rule checker flags the use of comparison operators, add a comment justifying the result. See:

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class myClass
{ 
    int data;
public:
    myClass& operator+=(myClass const& oth);
    friend myClass const operator+(myClass const& lhs, // Noncompliant: Use of friend keyword
                                   myClass const& rhs);

};

operator+ is a friend function of class myClass and can access its private member, data. The presence of this friend function violates the rule.

Check Information

Group: Member Access Control
Category: Required, Automated

Version History

Introduced in R2019a