PDA

View Full Version : [C++] Dynamic object creation with array and non-default constructor


MTsoul
12-29-2006, 05:44 PM
Suppose I want to dynamically create a non-fixed number of a certain class of objects at runtime.

int i;
cin >> i;
MyClass * my_objects;
my_objects = new MyClass(<some parameter>)[i];

This syntax is obviously wrong, according to my compiler. But you probably know what I'm trying to do. I want to create an array of i MyClass'es, each calling a constructor that has some parameter.

my_objects = new MyClass [i]; works, but I want to call a constructor other than the default constructor for each new object. How do I do this?

MTsoul
12-29-2006, 06:02 PM
Arg... never mind apparently it's not possible.

http://www.relisoft.com/book/lang/pointer/4memory.html

Consequently, if we are allocating an array of objects, there is no way to pass arguments to objects’ constructors. Therefore it is required that the objects that are stored in such an array have a no-argument constructor. In particular, it's okay if no constructor is defined for a given class-—we are allowed to allocate an array of such objects. No constructors will be called during initialization.

Booo!