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];
- An Abstract class is one whose instance CANNOT be created. - Creating an Array which holds the Object Reference Variable of that Abstract class are just the references not the object itself.
To make a dynamic array that stores any values, we can turn the class into a template: template <class T> class Dynarray { private: T *pa; int length; int nextIndex; public: Dynarray(); ~Dynarray(); T& operator[](int index); void add(int val); int size(); };
You cannot create instances of abstract classes, but you can assign concrete derived instances to pointers or references of the base class.
Master C and Embedded C Programming- Learn as you go In C++, a dynamic array can be created using new keyword and can be deleted it by using delete keyword.
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
You would need to create an array of pointers to Cat
:
Cat** catArray = new Cat*[200];
Even if the base class Cat
was concrete, you would still run headlong into object slicing if you created an array of Cat
.
Note that you should probably use a std::vector
instead of an array, and should probably use smart pointers to ensure your code is exception safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With