Main Content

MISRA C++:2008 Rule 5-2-2

A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of dynamic_cast

Description

Rule Definition

A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of dynamic_cast.

Rationale

A virtual base implies that multiple classes might be derived from it.

class Base{};
class childA: virtual public Base{};
class childB: virtual public Base{};
class childFinal: public childA, public childB{};;
In the preceding code, the derived classes childA and childB share the same instance of the class Base. The necessary pointer arithmetic is unknown at compile time when you cast from Base* to childA* or childB*. The offset of the child classes compared to Base is known only at run time.

Use dynamic_cast when downcasting a pointer to a virtual base class into a pointer to a child class. Using any other casting operation for this purpose results in an undefined behavior.

Polyspace Implementation

Polyspace® raises a violation if these conditions are met:

  • A virtual base class is downcast.

  • The casting operation is not done by using dynamic_cast

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 childA: virtual public Base{};
class childB: virtual public Base{};
class childFinal: public childA, public childB{};

void bar(){
	Base* pB;
	//...
	static_cast<childA*>(pB);//Noncompliant
}

In this example, the pointer to a virtual base pB is downcast to a pointer to a derived class. The information needed to cast pB to a childA* type is known at run time only. Using static_cast to perform these casts results in an undefined behavior. Polyspace raises a violation. This issue might also be reported as a compilation error.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b