Possible Duplicate:
Regular cast vs. static_cast vs. dynamic_cast
I don't quite get when to use static cast and when dynamic. Any explanation please?
static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.
While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them.
Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier. Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types.
In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.
Use dynamic_cast
when casting from a base class type to a derived class type. It checks that the object being cast is actually of the derived class type and returns a null pointer if the object is not of the desired type (unless you're casting to a reference type -- then it throws a bad_cast
exception).
Use static_cast
if this extra check is not necessary. As Arkaitz said, since dynamic_cast
performs the extra check, it requires RTTI information and thus has a greater runtime overhead, whereas static_cast
is performed at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With