…
1 basic type casting
1.1 const_cast
Remove the constness of variables. inmutable to mutable.
1.1.1 change non-const class members inside a const member function
1 2 3 4 5 6 7
| private: int roll; public: void fun() const { (const_cast<student *>(this))->roll = 5; }
|
1.1.2 pass const data to a function that doesn’t receive const
1 2 3 4 5 6
| int func(int *ptr){ return (*ptr + 10);}
const int val = 10; const int *ptr = &val; int *ptr1 = const_cast<int *>(ptr); func(ptr1);
|
1.1.3 undefined behavior to modify a value which is initially declared as const
1 2 3 4 5 6 7 8 9
| int func(int *ptr){ *ptr = *ptr + 10; return (*ptr); }
const int val = 10; const int *ptr = &val; int *ptr1 = const_cast<int *>(ptr); func(ptr1);
|
It is fine to modify a value which is not initially declared as const:
1 2 3
| int val = 10; ... func(ptr1);
|
1.1.4 safer then simple type casting
If the type of cast is not same as original object, the casting won’t happen.
1 2 3
| int a = 40; const int *b = &a; char *c = const_cast<char *>(b);
|
1.1.4 can be used to cast away volatile attribute
1 2 3
| int a = 40; const volatile int *b = &a; int *c = const_cast<int *>(b);
|
1.2 static_cast
1.2.1 cannot used to cast fro primitive data type pointers
1 2 3 4 5 6
|
int* q = (int*)&c; int* p = static_cast<int*>(&c);
|
1.2.2 able to call the conversion operator of the class if it is defined
1 2 3 4 5 6 7 8
| class A{ operator string(){} };
string str2 = static_cast<string>(obj);
|
1.2.3 used cast from Derived to Base class
1 2 3 4 5
| class Base {}; class Derived : public Base {};
Derived d1; Base* b2 = static_cast<Base*>(&d1);
|
1.2.4 cast to and from void pionter
1 2 3
| int i = 10; void* v = static_cast<void*>(&i); int* ip = static_cast<int*>(v);
|
1.3 dynamic_cast
downcasting
1.4 reinterpret_cast