anurag86
anurag86

Reputation: 209

Cast not shown correctly

In the sample code below, why

a is assigned as 004609CC instead of 004609C0? I was expecting a,b, and c to point to the same address. And why dynamic_Cast(a) changes the address to 004609C0

class A1
{public:
    unsigned a1;
    int a2;
    virtual ~A1() { }
};

class B1
{public:
    unsigned b1;
    int b2;
    virtual ~B1() { }
};

class C1 : public B1, public A1
{public:
    unsigned c1;
    virtual ~C1(){}
};


int main()
{
    C1* c = new C1;
    A1* a = c;
    B1* b = c;


    std::cout << static_cast<void*>(a) << "\n"; //004609CC Why not 004609C0?
    std::cout << static_cast<void*>(b) << "\n"; //004609C0
    std::cout << static_cast<void*>(c) << "\n"; //004609C0
    std::cout << dynamic_cast<C1*>(a) << "\n"; //004609C0  


//  delete b;
}

Upvotes: 0

Views: 34

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

When you look at the object layout of objects with multiple inheritance you'll basically have the base subobjects somewhere in the object. For example, the object could look something like this:

+-------+
+ +---+ +
| | B | |
| +---+ |
| +---+ |
| | A | |
| +---+ |
| C mem |
+-------+

When you have a pointer to a B or an A object it doesn't know that it is embedded into an object with multiple inheritance. Correspondingly either the pointer to the B subobject or the pointer to the A subobject cannot have the same address as the C object. Potentially, neither object has the same address as C, e.g., when the ABI specifies that the C members have to precede the base class subobjects (I'm not aware of any system which does this, though).

Upvotes: 3

Related Questions