Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 420
101010110101 Avatar asked Apr 27 '10 00:04

101010110101


People also ask

Can we create array of abstract class?

- 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.

How do you create a dynamic array of classes?

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(); };

Can we create array of abstract class in C++?

You cannot create instances of abstract classes, but you can assign concrete derived instances to pointers or references of the base class.

Can we create a dynamic array?

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.


2 Answers

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

like image 70
Jasmeet Avatar answered Oct 11 '22 17:10

Jasmeet


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.

like image 36
James McNellis Avatar answered Oct 11 '22 17:10

James McNellis