C++: Casting my object to a different superclass results in a different pointer address
I'm learning C++, trying to write good, polymorphic code, and running in to some confusion. I have a class Er_1Sine which has two superclasses: "Generator" and "Triggerable".
Er_1Sine looks like this:
class Er_1Sine : public Generator, public Triggerable{
}
If I create a "Generator" pointer (gen), setting it to "er1", the pointer address matches the address of "er1". However, the address of my "Triggerable" pointer, "trig", doesn't match. What's going on here? is trig not pointing to the same object that er1 and gen are?
er1 = new Er_1Sine();
Generator *gen = er1;
Triggerable *trig = er1;
printf("\n\n er1 as Er_1Sine: %p \n", er1);
// outputs: "er1 as Er_1Sine: 0x4d28920"
printf("er1 开发者_开发知识库as Generator address: %p \n", gen);
// outputs: "er1 as Generator address: 0x4d28920"
printf("er1 as Triggerable address: %p \n\n", trig);
// outputs: er1 as Triggerable address: 0x4d289f8
This is multiple inheritance - base class sub-objects are at different offsets withing the child instance, thus different addresses. It's the compiler front-end that has to adjust the pointer values during the implicit upcasts.
while not entirely correct, you can think of your compound class as 2 seperate objects stacked on top of eachother. The one you declared first being the top (same address) and the one declared second underneath (hence a different address).
One pointer points to the Generator
part of the class, the other pointer points to the Triggerable
part. They can't be the same pointer, because Generator and Triggerable are different.
With multiple inheritance, different base classes can have different memory addresses within the child object.
精彩评论