Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting double pointers of base classes

I have an Abstract class, say Animal. From this class, I have many inheriting classes, such as Cat, Dog, Mouse. I have a method that I want to be able to take pointers to pointers of these objects. So void someMethod(Animal **anAnimal);

How is this accomplished? It seems I am not able to cast upwards like this. I am trying the following:

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

//where someMethod has the method signature...
void someMethod(Animal **anAnimal);

What am I doing wrong, and how can I accomplish what I'm attempting?

like image 240
vapo Avatar asked Oct 28 '25 22:10

vapo


1 Answers

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.

like image 200
James McNellis Avatar answered Oct 30 '25 14:10

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!