Main Content

MISRA C++:2008 Rule 10-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 MISRA C++:2008 Rule 10-1-1. Rule 10-1-1 forbids the use of a virtual base anywhere in your code because a virtual base can lead to potentially confusing behavior.

Rule 10-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 10-1-1 but not rule 10-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 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

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.

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

Check Information

Group: Derived Classes
Category: Required

Version History

Introduced in R2013b