Casting double pointers of base classes

后端 未结 3 1692
遇见更好的自我
遇见更好的自我 2021-01-20 10:17

I have an Abstract class, say Animal. From this class, I have many inheriting classes, such as Cat, Dog, Mouse. I have

相关标签:
3条回答
  • 2021-01-20 10:47

    You need to introduce a temporary of type Animal*:

    Dog *d = new Dog(x); //some parameter x.
    Animal *a = d;
    Animal **animal = &a;
    someMethod(animal);
    

    The reason for this is that &d is Dog**, which cannot be converted to Animal** even if Dog* can be converted to Animal*.

    Normally you 'd fix this inline using something like this (warning -- does not compile!):

    Dog *d = new Dog(x); //some parameter x.
    Animal **animal = &(static_cast<Animal*>(d));
    someMethod(animal);
    

    However, this is not possible because the return value of static_cast is a temporary (technically, its a rvalue) so you cannot get its address. Therefore, you need the extra Animal* local to make this work.

    0 讨论(0)
  • 2021-01-20 10:49

    Going to have to do a cast.

    Animal **animal = (Animal **)&d;
    
    0 讨论(0)
  • 2021-01-20 10:50

    You need an Animal*:

    Dog* d = new Dog(x);
    Animal* a = d;
    Animal** animal = &a;
    someMethod(animal);
    

    An Animal** can only point to an Animal*. It would be very bad if it could point to a Dog*. If it could, you could do something like this:

    Dog* d = new Dog(x);
    Animal** animal = &d;
    *animal = new Hippopotamus();
    

    Now d points to a Hippopotamus, which is very wrong indeed.

    0 讨论(0)
提交回复
热议问题