Wednesday, March 7, 2007

Initialization of Array Elements

Because I get asked this question over and over again: when creating
an array of some type there is no way to call something else but the
default constructor for each element.
If you need to pass some initaliziation information to the constructor I see two possiblities

set some static variable and let the default constructor consider it

create an array of pointers, iterate over it and call new for each obejct

The second approach is furthermore necassary if each element must be initialized differently.
If somebody knows something better I am eager to hear about it

Update

If the array size is known at compile time one can say things straight away like this:

thingy arr7[42] = {1, argv[1], thingy(3.0)};

where the class thingy has a default constructor, one for integers, one for const characters and an explicit one for doubles.