Junior — Middle
In which cases is it recommended to use static_cast in C++?
sobes.tech AI
Answer from AI
static_cast in C++ is recommended for:
- Converting between compatible types, for example, from
inttodoubleor vice versa. - Casting pointers or references in a class hierarchy upwards (upcasting), when it is safe and explicit.
- Converting
void*to a pointer to a specific type.
static_cast does not perform runtime checks, so it should be used when you are confident in the correctness of the conversion.
Example:
class Base {};
class Derived : public Base {};
Derived d;
Base* b = static_cast<Base*>(&d); // safe upcast
int i = 10;
double dval = static_cast<double>(i); // int -> double