How to allocate memory for an array of instances using an abstract class?

I have an abstract class defining a pure virtual method in C ++:

class Base { Base(); ~Base(); virtual bool Test() = 0; }; 

I have subclassed this with a number of other classes (which provide an implementation for Test ()), which I will call A, B, C, etc. Now I want to create an array of any of these types using this base class:

 int main(int argc, char* argv[]) { int size = 0; Base* bases = new Base[10]; bases[size++] = new A(); bases[size++] = new B(); for (int i = 0; i < size; i++) { Base* base = bases[i]; base->Test(); } } 

(Sorry for any mistakes I could make, I am writing this on the fly to provide a simple example).

The problem is that I cannot create an instance of the array, because for this I will need to create an instance of the base class (which it cannot do as abstract). However, without doing this, he did not allocate the memory necessary for assigning indexes to the array, and thus provides a segmentation error when trying to access this memory. I got the impression that itโ€™s not a good practice to mix new ones and delete using malloc and for free.

I might be confused about how this should be used, and I should try to use templates or some other mechanism for this, but I hope I have provided enough information to illustrate what I'm trying to do.

So what is the best way to do this and how do I get around this problem of allocating memory to an abstract class?

Thanks Dan

+3
source share
3 answers

There is only a slight misunderstanding in this code. Instead of highlighting the base objects, you need to select pointers. A pointer can exist at any time. A pointer to an abstract class, an incomplete type, and even an invalid one:

 int main(int argc, char* argv[]) { int size = 0; Base** bases = new Base*[10]; bases[size++] = new A(); bases[size++] = new B(); for (int i = 0; i < size; i++) { Base* base = bases[i]; base->Test(); } } 
+12
source

First make sure your destructor is also declared virtual:

 virtual ~Base(); 

You better keep an array of pointers to instances:

 Base** bases = new Base *[10]; 
+6
source

An array relies on its entire element of the same size. When you have C ++ classes derived from the same base, instances can be of any size at all. So, regardless of whether the database is abstract or not, you cannot allocate an array of base instances, and then place derivative instances there.

As the other answers say, you need to use pointers. Select an array of pointers to the base, and then select the various derived instances and store the pointer to them in the array.

+5
source

All Articles