AUTOSAR C++14 Rule A10-3-5
A user-defined assignment operator shall not be virtual
Description
Rule Definition
A user-defined assignment operator shall not be virtual.
Rationale
Defining an assignment operator as virtual in a base class indicates
that you want to override it in the derived classes. Overriding the assignment operator in
derived classes can lead to undefined behavior and run-time errors. Consider this code
snippet where a virtual assignment operator is overridden in two derived
classes.
class Base {public:
virtual Base& operator=(Base const& oth) = 0;
//...
};
class Derived public: Base{ public:
Derived& operator=(Base const& oth) override{/*...*/}
//...
};
class Derived2 public: Base{public:
Derived2& operator=(Base const& oth) override{/*...*/}
//...
};
main(){
Derived d1;
Derived2 d2;
d1 = d2;
}Derived::operator= and Derived2::operator= overrides
Base::operator=, their parameter lists must be identical.
Derived::operator=takes reference to aBaseobject as input and returns a reference toDerived.Derived2::operator=takes reference to aBaseobject as input and returns a reference toDerived2.
The Derived::operator= accepts references to both
Base and Derived class objects because references to
derived classes are type-compatible with their base classes. Similarly, the
Derived2::operator= also accepts references to both
Base and Derived2 class objects. Assigning a
Derived object to a Derived2 object in
d1=d2 produces no compilation error. The objects d1
and d2 are unrelated. Assigning, copying, or moving operations between
such unrelated objects are undefined and can lead to run-time errors.
To avoid undefined behavior and run-time errors, keep user-defined assignment operators as non-virtual. This rule applies to these operators:
Assignment
Copy and move assignment
All compound assignment
Polyspace Implementation
Polyspace® flags the declaration of any virtual assignment operators in a base class.
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
Check Information
| Group: Derived classes |
| Category: Required, Automated |
Version History
Introduced in R2020a