Main Content

AUTOSAR C++14 Rule A10-3-3

Virtual functions shall not be introduced in a final class

Since R2020a

Description

Rule Definition

Virtual functions shall not be introduced in a final class.

Rationale

Declaring a function as virtual indicates that you intend to override the function in a derived class with a different implementation. The same function can then interact differently with different classes of a hierarchy. When you explicitly specify a class as final, you cannot derive a class from it. Because you cannot derive classes from a final class, do not introduce virtual functions in a final class. Specify all virtual functions in a final class by using the specifier final.

Polyspace Implementation

Polyspace® flags the declaration of virtual functions in a final class. Polyspace does not flag virtual functions in a final class that uses the specifiers override final or virtual final.

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

#include <cstdint>
class Base
{
public:
	virtual ~Base() = default;
	virtual void F() noexcept = 0;
	virtual void G() noexcept {/*...*/}
	virtual void Y() noexcept {/*...*/}
};
class Derived final : public Base
{
public:

	void G() noexcept override{/*...*/} //Noncompliant
	virtual void Z() noexcept{/*...*/}  //Noncompliant
	virtual void H() noexcept = 0;    //Noncompliant
	void F() noexcept final{/*...*/}    //Compliant
	void Y() noexcept override final{/*...*/}    //Compliant
};

The functions Derived::G(), Derived::Z(), and Derived::H() are virtual functions that are not specified as final. Their declarations indicate that some functions in a derived class might override these functions. The class Derived is specified as final. That is, there are no derived classes from this class. The declarations of Derived::G(), Derived::Z(), and Derived::H() are inconsistent with the declaration of their class Derived. Polyspace flags the declarations of the functions. The functions Derived::F() and Derived::Y() are declared as final. These declaration comply with this rule.

Check Information

Group: Derived classes
Category: Required, Automated

Version History

Introduced in R2020a

expand all