Main Content

MISRA C++:2008 Rule 10-1-1

Classes should not be derived from virtual bases

Description

Rule Definition

Classes should not be derived from virtual bases.

Rationale

The use of virtual bases can lead to many confusing behaviors.

For instance, in an inheritance hierarchy involving a virtual base, the most derived class calls the constructor of the virtual base. Intermediate calls to the virtual base constructor are ignored.

Polyspace Implementation

Polyspace® raises a violation if a class is derived from a virtual 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 raises a violation when the Intermediate class is derived from the class Base with the virtual keyword.

The following behavior can be a potential source of confusion. 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 R2013b