read the following program which is using reinterpret_cast.
#include <iostream>
class A
{
public:
A() : m_i(0) { }
protected:
int m_i;
};
class B
{
public:
B() : m_d(0.0) { }
protected:
double m_d;
};
class C : public A , public B
{
public:
C() : m_c('a') { }
private:
char m_c;
};
int main()
{
C c;
A *pa = &c;
B *pb = &c;
bool z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb));
std::cout << z;
return 0;
}
After running this program it prints 0, can anyone explain why z is coming false in this program??
Can anyone explain how reinterpret cast is working in this code
reinterpret_cast<char*>(pa)
evaluates to a pointer of type char*
whose numerical value is the same as that of pa
. Use of:
bool z = (pa == pb);
leads to a compiler error since A
and B
are not directly related. Use of
bool z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb));
allows you to compare the numerical values of pa
and pb
.
After running this program it prints 0, can anyone explain why z is coming false in this program??
The numerical values of pa
and pb
are not same. Hence, the result. You can use:
cout << "pa: " << std::hex << (void*)pa << std::endl;
cout << "pb: " << std::hex << (void*)pb << std::endl;
to print those values and convince yourself that they are not same.
If you look at the memory layout of a C
, it looks something like:
+------+
| m_i | // The A sub-object
+------+
| m_d | // The B sub-object
+------+
| m_c |
+------+
When you use
C c;
A* pa = &c;
B* pb = &c;
pa
points to the A
sub-object of C
and pb
points to the B
sub-object of C
. As you can see from the picture, there is an offset between the A
sub-object and the B
sub-object. Hence, the numerical values of pa
and pb
are different. The most likely differ by sizeof(m_i)
.