Main Content

AUTOSAR C++14 Rule M10-1-2

A base class shall only be declared virtual if it is used in a diamond hierarchy

Description

Rule Definition

A base class shall only be declared virtual if it is used in a diamond hierarchy.

Rationale

This rule is less restrictive than AUTOSAR C++14 Rule M10-1-1. Rule M10-1-1 forbids the use of a virtual base anywhere in your code because a virtual base can lead to potentially confusing behavior.

Rule M10-1-2 allows the use of virtual bases in the one situation where they are useful, that is, as a common base class in diamond hierarchies.

For instance, the following diamond hierarchy violates rule M10-1-1 but not rule M10-1-2.

class Base {};
class Intermediate1: public virtual Base {};
class Intermediate2: public virtual Base {};
class Final: public Intermediate1, public Intermediate2 {};

Polyspace Implementation

Polyspace® flags a class if the class is used as a virtual base in a single and linear class hierarchy. In such a hierarchy, virtual bases are unnecessary.

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 A{};
class B: public virtual A{};
class C: public virtual B{}; //Noncompliant

class alpha{};

class beta: public virtual alpha{};
class gamma: public virtual alpha{};
class omega: public beta, public gamma{}; //Compliant

In this example, the classes B and C in the linear hierarchy A->B->C uses virtual base classes. In this hierarchy, using virtual base classes is unnecessary and might cause confusion. Polyspace raises a violation. The class hierarchy alpha->...->omega is a diamond hierarchy and in this case, the use of virtual base classes is necessary. Polyspace does not flag this class hierarchy.

Check Information

Group: Derived Classes
Category: Required, Automated

Version History

Introduced in R2019a