Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static cast versus dynamic cast [duplicate]

Tags:

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?

like image 874
rayimag Avatar asked Aug 10 '09 13:08

rayimag


People also ask

What is the difference between static_cast and dynamic_cast?

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.

Is static_cast faster than dynamic_cast?

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.

What is the difference between static_cast dynamic_cast Const_cast and Reinterpret_cast?

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.

Why is static_cast better than C-style cast?

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.


1 Answers

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.

like image 174
Nick Meyer Avatar answered Oct 06 '22 23:10

Nick Meyer