Main Content

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

Casts from a base class to a derived class should not be performed on polymorphic types

Description

Rule Definition

Casts from a base class to a derived class should not be performed on polymorphic types.

Rationale

Explicitly casting a polymorphic base class into a derived class bypasses the layers of abstraction in the implementation hierarchy, resulting in increased coupling and dependency between the classes.

When using a polymorphic class, avoid performing explicit downcasts. A pointer to the polymorphic base class does not require explicit casting into a pointer to a derived class.

Polyspace Implementation

Polyspace® raises a violation if a base class is cast to a derived 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{ //Abstract base class
	//...
public:
	virtual bool getStatus() const = 0;
};
class Derived: public Base{
	//...
public:
	virtual bool getStatus() const{ //Implementation of getStatus()
		//...
	}
};
void printStatus(const Base& B){
	const Derived* D = dynamic_cast<const Derived*>(&B);//Noncompliant
	D->getStatus();
}
void printStatus_compliant(const Base& B){
	B.getStatus();//Compliant
}

In this example, the Base class pointer B is cast to a Derived class pointer in printStatus. This cast is noncompliant and Polyspace raises a violation. The function getStatus_compliant() shows a compliant implementation of this functionality, where virtual functions invoke the Derived class member function through a pointer to the Base class.

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2013b