reinterpret_cast is a type of casting operator used in C++.
- It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.
- It does not check if the pointer type and data pointed by the pointer is same or not.
Syntax :
data_type *var_name =
reinterpret_cast <data_type *>(pointer_variable);
Return Type
- It doesn’t have any return type. It simply converts the pointer type.
Parameters
- It takes only one parameter i.e., the source pointer variable (p in above example).
CPP
#include <iostream>
using namespace std;
int main()
{
int * p = new int (65);
char * ch = reinterpret_cast < char *>(p);
cout << *p << endl;
cout << *ch << endl;
cout << p << endl;
cout << ch << endl;
return 0;
}
|
Purpose for using reinterpret_cast
- reinterpret_cast is a very special and dangerous type of casting operator. And is suggested to use it using proper data type i.e., (pointer data type should be same as original data type).
- It can typecast any pointer to any other data type.
- It is used when we want to work with bits.
- If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required.
- It is only used to typecast any pointer to its original type.
- Boolean value will be converted into integer value i.e., 0 for false and 1 for true.
CPP
#include <bits/stdc++.h>
using namespace std;
struct mystruct {
int x;
int y;
char c;
bool b;
};
int main()
{
mystruct s;
s.x = 5;
s.y = 10;
s.c = 'a' ;
s.b = true ;
int * p = reinterpret_cast < int *>(&s);
cout << sizeof (s) << endl;
cout << *p << endl;
p++;
cout << *p << endl;
p++;
char * ch = reinterpret_cast < char *>(p);
cout << *ch << endl;
ch++;
bool * n = reinterpret_cast < bool *>(ch);
cout << *n << endl;
cout << *( reinterpret_cast < bool *>(ch));
return 0;
}
|
Program 2
CPP
#include <iostream>
using namespace std;
class A {
public :
void fun_a()
{
cout << " In class A\n" ;
}
};
class B {
public :
void fun_b()
{
cout << " In class B\n" ;
}
};
int main()
{
B* x = new B();
A* new_a = reinterpret_cast <A*>(x);
new_a->fun_a();
return 0;
}
|
Related link :
https://www.geeksforgeeks.org/casting-operators-in-c-set-1-const_cast/
https://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast” rel=”noopener” target=”_blank
http://forums.codeguru.com/showthread.php?482227-reinterpret_cast-lt-gt-and-where-can-it-be-used
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/keyword_reinterpret_cast.htm
https://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast