What is static_cast for, how does it work and where is it used?
static_cast has a lot of different uses. Its idea is this: it's a limited C-style cast. The restriction is needed because a C-style cast can cast anything to anything (well, almost), and thus can hide the error. For example, you can accidentally cast
const char* to
char* , causing a crash on some systems with hardware support for const memory.
static_cast won't let you do that.
Most of the time, when you want to do an explicit type conversion (and I hope this is rare enough), you want
The formal list of everything that
static_cast can do is very long , I will list only the most important things that it can (and also that it can't ):
What is possible:
- Converting a pointer to a parent class to a pointer to a child class. The object pointed to must be a valid child class, otherwise undefined behavior. If you're unsure and want to check if an object has the right subclass, use
dynamic_cast(it's designed specifically for that).
- Conversions between numeric types.
unsigned int– all of them can be cast into each other using
- You can cast any expression to
void. The result will be evaluated and discarded (but the side effects will, of course, be executed).
static_castcan cast the
nullptrconstant to any pointer type. This is usually not necessary and you can rely on implicit type conversion, but sometimes (for example, to select the desired function overload), this can be useful.
What is not allowed:
- Conversion between pointers to basically incompatible types. For example, a pointer to
doublecannot be cast to a pointer to
int. For type safety tricks, use
- Pointers to types, as well as types themselves with incompatible
volatileattributes. If you need to break const-correctness, use
- Of course, you can't cast a member function pointer to a regular function pointer, or a code pointer to a data pointer. For such dirty hacks, use
Another reason to use
static_cast (as well as other C++-specific type conversions) is that it can be easily found in sources, both by eyes and by search tools. Cish casting (especially its functional variety) is very easy to miss in the code.
For comparison, the "usual" type conversion (C-style cast) is equivalent to the following sequence:
const_castcannot produce the desired result, then
static_cast(but with a cast to an underdeclared type allowed)
- If it still doesn't work, then the compiler tries to add
static_castto the tail of
- If this fails, then
- … and if it fails, then
const_castappended to it.