Main Content

MISRA C++:2023 Rule 13.1.2

An accessible base class shall not be both virtual and non-virtual in the same hierarchy

Since R2024b

Description

Rule Definition

An accessible base class shall not be both virtual and non-virtual in the same hierarchy.

Rationale

You use virtual inheritance to prevent the creation of multiple copies of a base class Base subobject in a derived class that inherits class Base more than once through intermediate classes.

If the same class is inherited virtually and non-virtually in the same hierarchy, multiple instance of the base class subobject can exist, which might not be the intent of the developer.

Polyspace Implementation

The coding rule checker reports a violation in the declaration of the most derived class for each derived class that inherits the base class non-virtually.

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 Base {};
class Intermediate1: virtual public Base {};
class Intermediate2: virtual public Base {};
class Intermediate3: public Base {};
class Final: public Intermediate1, Intermediate2, Intermediate3 {}; //Noncompliant

In this example, the class Base is inherited in Final virtually through the classes Intermediate1 and Intermediate2, and non-virtually through the class Intermediate3.

Polyspace reports a violation in the declaration of Final on the class Intermediate3 because the non-virtual inheritance through this class results in at least two copies of a Base subobject in the Final object.

Check Information

Group: Derived classes
Category: Required

Version History

Introduced in R2024b