Useful tips

What is difference between dynamic_cast and static_cast in C++?

What is difference between dynamic_cast and static_cast in C++?

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.

When should I use dynamic_cast?

dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited).

What does static_cast mean in C++?

type float
The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What is the difference between static_cast and Reinterpret_cast?

static_cast only allows conversions like int to float or base class pointer to derived class pointer. reinterpret_cast allows anything, that’s usually a dangerous thing and normally reinterpret_cast is rarely used, tipically to convert pointers to/from integers or to allow some kind of low level memory manipulation.

What is the use of dynamic_cast?

Although dynamic casts have a few different capabilities, by far the most common use for dynamic casting is for converting base-class pointers into derived-class pointers. This process is called downcasting. Using dynamic_cast works just like static_cast.

What is a static cast?

Static Cast: This is the simplest type of cast which can be used. It is a compile time cast .It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones). For e.g.

What is dynamic cast?

Dynamic casts can be used to safely cast a superclass pointer (or reference) into a pointer (or reference) to a subclass in a class hierarchy. If the cast is invalid because the the real type of the object pointed to is not the type of the desired subclass, the dynamic will fail gracefully.