CRITICAL
Rule Definition
You can cast from pointer to base to pointer to derived only if the pointed-to object really is of the derived type (or a type derived from the derived type). Using a 'static_cast' will always succeed, even when the pointed-to object is of the wrong type. Using 'dynamic_cast' will check the real type of this object before performing the cast and is safer to use.
See also rule "Casting from pointer to base Class to pointer to derived Class should be done through 'dynamic_cast' or 'static_cast'" (id 8078).
Additionally, casting from a base class to a derived class is often a sign of base design and should usually be avoided.
Remediation
Use 'dynamic_cast' to cast pointers to base class to pointer to derived class.
Violation Code Sample
class A
{
};
class B : public A
{
};
void f(A *p)
{
B* pb = static_cast<B*>(p); // Violation
// Use pb
}
Fixed Code Sample
void f(A *p)
{
B* pb = dynamic_cast<B*>(p);
if (!pb)
{
// Not the expected type, handle the error
}
else
{
// Use pb
}
}
Reference
MISRA C++
"C++ coding standard":http://www.gotw.ca/publications/c++cs.htm (Sutter/Alexandrescu) Item 93
Related Technologies
C++
Technical Criterion
Programming Practices - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.