Main Content

MISRA C++:2023 Rule 13.1.1

Classes should not be inherited virtually

Since R2024b

Description

Rule Definition

Classes should not be inherited virtually.

Rationale

While virtual inheritance helps to solve the diamond inheritance problem, the use of virtual base classes can introduce confusing behavior. For example, during name resolution, a method in a derived class can hide methods with the same name in base classes further up the inheritance hierarchy, which might result in a call to a function with the wrong number of arguments

Polyspace Implementation

The coding rule checker reports a violation for any class that inherits virtually from 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

expand all

class Base {};
class Intermediate: public virtual Base {}; //Noncompliant
class Final: public Intermediate {};

In this example, the rule checker reports a violation for the class Intermediate because it inherits virtually from the class Base. The virtual inheritance can result in the following potentially confusing behavior.

When you create an object of type Final, the constructor of Final directly calls the constructor of Base. Any call to the Base constructor from the Intermediate constructor are ignored. You might see unexpected results if you do not take into account this behavior.

Check Information

Group: Derived classes
Category: Advisory

Version History

Introduced in R2024b