Reputation: 671
I am wondering why I cannot initialize an array of abstract objects to the stack but not the heap.
Here is some C++ code similar to mine that fails on the last line. I'm mainly just curious with the reasons behind this problem dealing with the heap vs. the stack. Thanks in advance!
#define ARRAY_SIZE 10
class Obj {
public:
virtual void fn() =0;
};
class Sub : public Obj {
public:
void fn() {
// ...
}
};
Obj * o1_array[ARRAY_SIZE];
Obj * o2_array = new Obj[ARRAY_SIZE]; // Compiler Error
Upvotes: 0
Views: 619
Reputation: 227508
You are doing two very different things. In the "stack" case,
Obj * o1_array[ARRAY_SIZE];
you are initializing an array of pointers. You don't need a complete or non-abstract type for this. In the "heap" case,
Obj * o2_array = new Obj[ARRAY_SIZE];
you are initializing an array of objects on the RHS and assigning the address of the first element to a pointer in the LHS. You need a complete, non-abstract type to build the array. If you want a dynamically-sized collection of pointers, a good bet is to use a container of pointers (assuming something else takes care of the management of the pointees' lifetime) or a container of smart pointers (where the smartness of the pointer decides who manages the pointee).
Non-managing:
std::vector<Obj*> o1_array(ARRAY_SIZE);
Managing (unique ownership):
std::vector<std::unique_ptr<Obj>> o1_array(ARRAY_SIZE);
For more options on containers managing "pointers", see the boost pointer container library.
Upvotes: 6