CyberLuc CyberLuc - 1 month ago 18
C++ Question

C++ using new to create object array with initializer

I wrote a class, something like this (just for demonstration) :

class cls{
public:
cls(int a):value(a){}
private:
int value;
};


And I want to dynamically create an array, each element initialized to a specific value like 2:

cls *arr = new cls[N](2);


But g++ reported 'error: parenthesized initializer in array new'.

I searched the Internet, but only to find similar questions about basic types like
int
and
double
, and answer is NO WAY.

Suppose the class must be initialized, how to solve the problem? Do I have to abandon constructer?

Answer

You can:

cls *arr = new cls[3] { 2, 2, 2 };

If you use std::vector, you can:

std::vector<cls> v(3, cls(2));

or

std::vector<cls> v(3, 2);