The first two lines of output in the following code are two blank lines and the third and fourth lines are two unequal big numbers such like: 19147336 19147192
class A {
public:
A() : m_i(0) { }
protected:
int m_i;
};
class B {
public:
B() : m_d(0.0) { }
protected:
double m_d;
};
int main() {
A *pa = new A;
B *pb = new B;
std::cout << reinterpret_cast<char*>(pa) << std::endl;
std::cout << reinterpret_cast<char*>(pb) << std::endl;
std::cout << (int)reinterpret_cast<char*>(pa) << std::endl;
std::cout << (int)reinterpret_cast<char*>(pb) << std::endl;
return 0;
}
I wonder what is exactly the return of reinterpret_cast in the above code. Thanks!
You are doing undefined behaviour. The compiler is free to to generate code that does literally anything, including creating a robot to travel back in time to douse the parents of K&R with morning after pills to prevent C from being invented in the first place.
In the first two cases above, your compiler is instead interpreting the bytes of an int
and a double
with value 0
as a nul-terminated array of characters, and seeing it as a 0 length buffer, so printing nothing.
In the second set of (int)
cast cases, it is giving you an integer representation of the lower sizeof(int)
bytes of the pointer value gotten from new
.
Neither of these are surprising, but neither of these can be relied upon. From strict aliasing to optimization, the compiler can do insane things when you engage in undefined behaviour, and even if you do not attach a time machine or robots, the effects of UB can occur before the code with UB runs.