How bad a cast is typically depends on the type of cast. There are legitimate uses for all of these casts, but some smell worse than others.
const_cast
is used to cast away const
ness (since adding it doesn't require a cast). Ideally, that should never be used. It makes it easy to invoke undefined behavior (trying to change an object originally designated const
), and in any case breaks the const
-correctness of the program. It is sometimes necessary when interfacing with APIs that are not themselves const
-correct, which may for example ask for a char *
when they're going to treat it as const char *
, but since you shouldn't write APIs that way it's a sign that you're using a really old API or somebody screwed up.
reinterpret_cast
is always going to be platform-dependent, and is therefore at best questionable in portable code. Moreover, unless you're doing low-level operations on the physical structure of objects, it doesn't preserve meaning. In C and C++, a type is supposed to be meaningful. An int
is a number that means something; an int
that is basically the concatenation of char
s doesn't really mean anything.
dynamic_cast
is normally used for downcasting; e.g. from Base *
to Derived *
, with the proviso that either it works or it returns 0. This subverts OO in much the same way as a switch
statement on a type tag does: it moves the code that defines what a class is away from the class definition. This couples the class definitions with other code and increases the potential maintenance load.
static_cast
is used for data conversions that are known to be generally correct, such as conversions to and from void *
, known safe pointer casts within the class hierarchy, that sort of thing. About the worst you can say for it is that it subverts the type system to some extent. It's likely to be needed when interfacing with C libraries, or the C part of the standard library, as void *
is often used in C functions.
In general, well-designed and well-written C++ code will avoid the use cases above, in some cases because the only use of the cast is to do potentially dangerous things, and in other cases because such code tends to avoid the need for such conversions. The C++ type system is generally seen as a good thing to maintain, and casts subvert it.