How to create a dynamic array of an Abstract class?

101010110101 picture 101010110101 · Apr 27, 2010 · Viewed 20.4k times · Source

Lets say I have an abstract class Cat that has a few concrete subclasses Wildcat, Housecat, etc.

I want my array to be able to store pointers to a type of cat without knowing which kind it really is.

When I try to dynamically allocate an array of Cat, it doesn't seem to be working.

Cat* catArray = new Cat[200];

Answer

Jasmeet picture Jasmeet · Apr 27, 2010

By creating an aray of pointers to Cat, as in

 Cat** catArray = new Cat*[200];

Now you can put your WildCat, HouseCat etc instances at various locations in the array for example

 catArray[0] = new WildCat();
 catArray[1] = new HouseCat();
 catArray[0]->catchMice(); 
 catArray[1]->catchMice();

Couple of caveats, when done
a) Don't forget deleting the instances allocated in catArray as in delete catArray[0] etc.
b) Don't forget to delete the catArray itself using

 delete [] catArray;

You should also consider using vector to automate b) for you