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
source share