CRITICAL
Rule Definition
Casting from pointer to base class to pointer to derived class should usually be done through 'dynamic_cast'. See rule #8060 for more information.
In performances-constrained situations, and if you know through another mean that the 'dynamic_cast' will succeed, you can instead call 'static_cast', which will be slightly more efficient. In this case, it is advised to write code that will check in debug builds that the assumption is true.
In any case, a C-style cast is unsafe to use, because it will be considered as a 'reinterpret_cast' if the classes are not related, and will do the wrong thing.
Remediation
Use 'dynamic_cast' or 'static_cast' to cast pointers to base class to pointer to derived class. See remediation example for more details.
Violation Code Sample
class A
{
};
class B : public A
{
};
void f(A *p)
{
B* pb = (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
}
}
In circumstances where the @dynamic_cast@ has been measured to cause unacceptable delay, a @static_cast@ could be used instead, but would benefit from being written this way:
template<class To, class From> To checked_cast(From* p)
{
assert(dynamic_cast<To>(p) == static_cast<To>(p) && "Error: Check cast failed");
return static_cast<To>(p);
}
void f(A *p)
{
B* pb = checked_cast<B*>(p);
// Use pb
}
Reference
MISRA C++
C++ Coding Standard (Sutter/Alexandrescu) Item 93, http://www.gotw.ca/publications/c++cs.htm
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.