Arrays and Inheritance

My question probably has a simple answer but I am not 100% sure on the syntax of replicating the following scenario.

Say I have 3 classes. The first class is called Animal. The other two classes both inherit from Animal and are called Cat and Dog. Next say I wanted to store an array of Animal objects but I want to be able to store both cats and dogs in the same array. I want to store 10 animals but in an unknown order of Cat and Dog objects.

What is the syntax for declaring an array such as the one described above? My first guess would be something along the lines of the following:

1
2
3
Animal animal_array* = new Animal[10];
animal_array[0]= new Dog;
animal_array[1] = new Cat
etc...

I am not sure if this would work as you are assigning a variable of type pointer to animal with a value of type pointer to dog/cat. Plus in this situation animal would be abstract and so having a pointer to object Animal wouldn't be allowed as Animal would have undefined function members.

I just read that a pointer to a derived class is type compatible with a pointer to its base class although I am still unsure of the syntax
Last edited on
To get your code to work, you could use

Animal* animal_array[10];

Practical solutions are
std::array<std::unique_ptr<Animal>, 10> animal_array;
or
boost::ptr_array<Animal, 10> animal_array;
(although vectors are often more useful)
Last edited on
Topic archived. No new replies allowed.