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
int i = 9;
char c = 'a';
int* q = (int*)&c; // pass at compile time, may fail at run time
int* p = static_cast<int*>(&c); //fails at compile time
float f = static_cast<float>(i); // convert object from one type to another
Base* pd = static_cast<Base*>(new Derived()); // convert pointer/reference from one type
// to a related type (down/up cast)
view raw staticcast.cpp hosted with ❤ by GitHub
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
class Base {
virtual void fun() { }
};
class Derived :public Base {
void fun() { }
};
int main()
{
Derived*pDerived = new Derived();
Base*pbase = new Base();
Base*pbase2 = pDerived;// this compiles alright
pbase = static_cast<Base*>(new Derived());//derived to base
pDerived = static_cast<Derived*>(new Base());//base to derived works fine, works on non polymorphic
pbase = dynamic_cast<Base*>(new Derived());//derived to base
pDerived = dynamic_cast<Derived*>(new Base());//base to derived returns null pointer works only if polymorphic
return 0;
}
view raw casting.cpp hosted with ❤ by GitHub
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