3

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?

1
  • 1
    Use a vector. You should be using one anyway. Commented Jul 24, 2014 at 3:06

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized. Seems vector only initializes once, then copy the one to the remaining objects.
@Twisx constructor called when you used cls(2) manually and passed it to vector initialisation. Then copy constructor used to fill elements.
5

Use a vector.

If you insist on using a dynamically allocated array instead of std::vector, you have to do it the hard way: allocate a block of memory for the array, and then initialize all the elements one by one. Don't do this unless you really can't use a vector! This is only shown for educational purposes.

cls* arr = static_cast<cls*>(::operator new[](N*sizeof(cls)));
for (size_t i = 0; i < N; i++) {
    ::new (arr+i) cls(2);
}
// ::delete[] arr;

2 Comments

Thanks, vector is enough for me.
Thank you for this obscure answer. It came in very handy for me in my use case: I needed a pointer to an array of objects that lack a default constructor to be queued to another thread which will later destroy the memory when it's no longer needed. I wouldn't have been able to do that with a vector. I'll admit it's less pretty, but it gets the job done.
1

You can also use vectors

#include <vector>

using namespace std;

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

int main() {

vector<cls> myArray(100, cls(2));

return 0;
}

That creates a vector (an array) with 100 cls objects initialized with 2;

1 Comment

Thanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.