Hi,
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'll refer to as A, B, C, etc. I now 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();
}
}
(Excuse any errors I might have made, I'm writing this on the fly to provide a simple example).
The problem is I can't instantiate the array as it would require creating an instance of the Base class (which it can't do as it's abstract). However, without doing this, it hasn't allocated the memory needed to assign to the indices of the array, and thus provides a segmentation fault when trying to access that memory. I am under the impression that it's not good practice to mix new and delete with malloc and free.
It may be that I have confused the way this should be used and I should be attempting to use templates or some other mechanism to do this, but hopefully I've provided enough information to illustrate what I'm attempting to do.
So what is the best way of doing this and how would I get around this problem of allocating memory to an abstract class?
Thanks, Dan