简体   繁体   中英

C++ multiple inheritance, confused with addresses of base classes in derived object

Why does code below print 01 ?
I expected 00 . Why does operator== return true in first case if addresses aren't equal?

#include <iostream>

class B1
{
    int m_i;
};

class B2
{
    double m_d;
};

class D
    : public B1
    , public B2
{
};

int main()
{
    D d;
    B2 *b2 = &d;

    std::cout << "d:\t" << reinterpret_cast<void*>(&d) << "\t" << &d << "\n";
    std::cout << "b2:\t" << reinterpret_cast<void*>(b2) << "\t" << b2 << "\n";


    std::cout << (reinterpret_cast<void*>(b2) == reinterpret_cast<void*>(&d));
    std::cout << (b2 == &d);

    return 0;
}

Gives output:

d:  0xbfd65fa4  0xbfd65fa4
b2: 0xbfd65fa8  0xbfd65fa8

01

When you compare b2 and &d without casting to void, the compiler is implicitly casting them to a common datatype - in this case, d is being implicitly casted to its B2 base class.

When you compare by casting to void, you get the true underlying address of the object, and since D inherits from B1 before B2 this is the address of its B1 base class.

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