UCSC -- Use C++ Style Casts
Go Up to C++ Audits
Description
Audit checks for C-style casts, which should be avoided. There are several casting operators specific to the C++ language, which should be used instead. These operators are intended to remove some of the ambiguity and danger inherent in C-style casting. These operators are:
- dynamic_cast—Use for conversion of polymorphic types.
- static_cast—Use for conversion of nonpolymorphic types.
- const_cast—Use to remove the const and volatile attributes.
- reinterpret_cast—Use for simple reinterpretation of bits.
Use the C++ operators listed here, instead of C-style casting. However, avoid using const_cast and reinterpret_cast, if possible. These operators have the same dangers as C-style casts, but they are still necessary in order to completely replace C-style casts.
Incorrect
return (Cat*)myAnimalPtr;
Correct
return dynamic_cast<Cat*>(myAnimalPtr);