Re: How to Call "Constructor with parameter" after new  allocation?
firstname.lastname@example.org ha scritto:
I want to allocate object arrays in heap with initializing them as a
You can't. You have to consider that "new T[n]" does not allocate "n
elements of type T" but *one array* made of "n elements of type T". This
makes a *big* difference. The new-initializer in a new-expression
provides argument to the constructor of the allocated object, but array
types only have one constructor: the default constructor that takes *no*
So, when allocating an array T[n], only these two syntaxes are legal:
new T[n]; // #1 new-initializer omitted
new T[n](); // #2 new-initializer is ()
there is no third case. The effect of the two syntaxes is different: #1
will use the default constructor if T is a non-POD class type and leave
the memory uninitialized in all other cases. #2 will perform
value-initialization, which very broadly speaking (see 8.5 for the
details) means that if there's a user-defined default constructor it is
called, otherwise the elements are zero-initialized.
In any case, there is no way to initialize the individual members to a
value which is not zero or the result of the default constructor.
On the other hand, new-expressions to allocate arrays is a very
error-prone technique that should be strongly discouraged except when
programming at a very low-level. It's much better to use a container and
std::vector in particular. For example:
allocates n ints and initializes each of them with 10.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]