0%

type casting operator

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); // pass a non-const data

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; // undefined behavior
return (*ptr);
}

const int val = 10; // iinitially declared as const
const int *ptr = &val;
int *ptr1 = const_cast<int *>(ptr);
func(ptr1); // pass a non-const data

It is fine to modify a value which is not initially declared as const:

1
2
3
int val = 10; // initially declared as non-const
...
func(ptr1); // it's fine

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); // complier error

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); // cast away volatile attribute

1.2 static_cast

1.2.1 cannot used to cast fro primitive data type pointers

1
2
3
4
5
6
// Pass at compile time,
// may fail at run time
int* q = (int*)&c;
int* p = static_cast<int*>(&c);

// error: invalid 'static_cast' from type 'int*' to type 'char*'

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{
// user defined conversion operator to string type
operator string(){}
};


// using static_cast for typecasting
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); // upcasting

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