简体   繁体   中英

Equality of pointers to classes in hierarchy

#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;

    const int x = (pa == &c) ? 1 : 2;
    const int y = (pb == &c) ? 3 : 4;
    const int z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb)) ? 5 : 6;

    std::cout << x << y << z << std::endl;

    return 0;
}

This code prints out 136 which would suggest that the first equality was true, second also but not the third. Since pa and pb are both set to &c the first two would make sense but then why would the third equality be false?

I ran this code in Visual C++ 2012 and used debugger to check the addresses:

pa == 0x003bfc90
pb == 0x003bfc98
&c == 0x003bfc90

Apparently, pa and pb don't point to the same address which would mean that the third equality should be false (and it is). But then why are the first two true? Could you explain to me what is going on here?

The two pointers do indeed have different values since they point to different sub-objects of c ; these two objects must exist at different locations.

Without reinterpret_cast , the equality comparison first looks for a suitable conversion to the same pointer type. This converts &c from C* to B* by modifying the pointer value to point to the B sub-object of c - exactly the same conversion that was applied when initialising pb . After that conversion, both pointers have the same value, and so compare equal.

reinterpret_cast means that the pointer should be converted to the target type without modifying its value, whether or not that conversion is meaningful. So, after that conversion, the pointers still have different values, and compare not equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM