Question:
What is static_cast for, how does it work and where is it used?
Answer:
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 static_cast
.
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.
int
,long
,char
,unsigned int
– all of them can be cast into each other usingstatic_cast
. - You can cast any expression to
void
. The result will be evaluated and discarded (but the side effects will, of course, be executed). -
static_cast
can cast thenullptr
constant 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
double
cannot be cast to a pointer toint
. For type safety tricks, usereinterpret_cast
. - Pointers to types, as well as types themselves with incompatible
const
and/orvolatile
attributes. If you need to break const-correctness, useconst_cast
. - 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
reinterpret_cast
.
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_cast
. - If
const_cast
cannot produce the desired result, thenstatic_cast
(but with a cast to an underdeclared type allowed) - If it still doesn't work, then the compiler tries to add
static_cast
to the tail ofconst_cast
. - If this fails, then
reinterpret_cast
. - … and if it fails, then
const_cast
appended to it.