How does the reinterpret_cast work?

Viewed 2184

I'm wondering how does reinterpret_cast work behind the scenes. I'm learning about it from a book, but i just don't get it. E.g. suppose i have the following part of code:

int a = 255;
char *pChar = reinterpret_cast<char*>(&a);

or

std::string str = "Hello";
char *pChar = reinterpret_cast<char*>(&str);

What will pChar pointed to in both examples, why i can't see anything when i try to print their contents, and of course how does reinterpret_cast work?

Edit: I know reinterpret_cast is pretty dangerous to use, and only want to use it to write bytes directly into a binary file from a block of memory. What i don't understand is that when i have an

int a = 255; (00 00 00 FF in memory)

and i want to treat the variable a as a series of bytes, char* :

char *pChar = reinterpret_cast<char*>(&a);

Will pChar point to the individual bytes of variable a (00 00 00 FF)?

So when i want to write into a binary file what the pChar pointed to:

a_file.write(reinterpret_cast<char*>(&a), sizeof(a));

It writes the individual bytes of variable a, right?

2 Answers
Related