Search code examples
c++arraysabstract-classabstract

How to create a dynamic array of an Abstract class?


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];

Solution

  • 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