About dynamic cast and address of base and derived objects

前端 未结 4 1937
名媛妹妹
名媛妹妹 2021-01-22 11:10

I was reading through some of effective c++ and I realized I may be incorrect in my thinking along the way.

class A
{
    public:
    void laka()
    {
        c         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 11:19

    Most implementations of inheritance put the first base class subobject at the beginning of the derived class, so you really need two base classes, both with data members, to be able to see this. Consider:

    #include 
    
    struct B1 { 
        int x; 
        virtual ~B1() { } 
    };
    
    struct B2 {
        int y;
        virtual ~B2() { }
    };
    
    struct D : B1, B2 { };
    
    int main() {
        D x;
        B1* b1_ptr = &x;
        B2* b2_ptr = &x;
        std::cout << "original address:     " << &x << "\n";
    
        std::cout << "b1_ptr:               " << b1_ptr << "\n";
        std::cout << "dynamic_cast b1_ptr:  " << dynamic_cast(b1_ptr) << "\n";
    
        std::cout << "b2_ptr:               " << b2_ptr << "\n";
        std::cout << "dynamic_cast b2_ptr:  " << dynamic_cast(b2_ptr) << "\n";
    }
    

    Example output (from my machine; your results will be similar):

    original address:     0030FB88
    b1_ptr:               0030FB88
    dynamic_cast b1_ptr:  0030FB88
    b2_ptr:               0030FB90
    dynamic_cast b2_ptr:  0030FB88
    

    This tells us that the B1 subobject of D is located at the beginning, so it has the same address as the D object of which it is a subobject.

    The B2 subobject is located at a different address, but when you use dynamic_cast on the pointer to the B2 subobject, it gives you the address of the D object of which it is a subobject.

提交回复
热议问题