C++ 11 feature: reinterpret_cast

“reinterpret_cast” has been introduced in C++ 11.

This cast should be carefully used.

* reinterpret_cast is used to convert one pointer to another pointer of any other type.

* It will not check if the pointer and the data pointed by the pointer are same or not.

Syntax of reinterpret_cast cast:

data_type *var_name = reinterpret_cast <data_type *>(pointer_variable);

using reinterpret_cast it can guarentee that if you cast it to a different type, then you again reinterpret_cast it back to the original type, you get the original value.

Example:

int a = new int();

void * b = reinterpret_cast<void*> (a);

int * c = reinterpret_cast<int*> (b);

Example of reinterpret_cast

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
    int* ptr = new int(70); 
    char* ch = reinterpret_cast<char*>(ptr); 
    cout << *ptr << endl; 
    cout << *ch << endl; 
    cout << ptr << endl; 
    cout << ch << endl; 
    return 0; 
} 

Output:

70
F
0xc97e70
F
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *