Saturday 20 June 2020

Casting

Implicit casting:
when we assign a float to integer, compiler implicitly casts it

Explicit casting.
We tell the compiler that I want this type to cast to another type, and we are aware of data loss that might occur.

const_cast
Used to cast away constness of a variable.
We can change non-const class member inside const member function.
We can pass const data to a function that wont take constant.
Undefined behaviour on modifying variable declared as const
It is safer

static_cast
Casting a float to int using static_cast.
It is compile-time cast
It performs a strict type checking.
Cannot cast incompatible types
Gives compilation error if matching types not casted

dynamic_cast
Can be used only with pointers and references to objects.
Always successful from derived to base
Base to derived is not allowed unless for polymorphic
dynamic_cast checks RTTI to return the complete valid object
Returns nullpointer in case it is not able to return the valid object
Throws bad_cast exception in case of reference.
Can cast void pointer to any class (even unrelated)
Can cast any type of pointer to void pointers

reinterpret_cast
Converts any type of pointer to any other type (whether related or not)

No comments:

Post a Comment