Basically you can't. As you've figured out, when you use
IndexAndSign* arr = new IndexAndSign[size];
C++ searches for the default (naked) constructor to allocate the correct amount of memory for your objects. But you can't provide naked constructor because of the initializer list due to the const members.
However, there are some loopholes:
- The default newbie-hiting aswer is "use
std::vector" eg.:
std::vector<IndexAndSign> arr;
for(int i=size; i-->0;){
int d=0; bool biP=true; // or something
arr.push_back(IndexAndSign(d, bIP));
}
However, there is a hidden problem with this solution: it uses the move constructor of your class. And if your class is a little complicated, the default move constructor provided by the compiler will be wrong (according to the rule of n).
- You can give a try to the pointer to pointer concept:
IndexAndSign** arr = new IndexAndSign*[size];
for(int i=size; i-->0;){
int d=0; bool biP=true; // or something
arr[i] = new IndexAndSign(d, bIP);
}
The backward of this solution, that if you want to access a member of your object, you have to use -> instead of . eg.:
std::cout << arr[0]->depth << std::endl;
Further reading is here
new[]to create your array. If you know the size at compile-time and it will not change at run-time, usestd::array, otherwise usestd::vector.std::vector<IndexAndSign>, and then add constructed elements later.new[]), the initialization is done. You can't go back and "undo" or "redo" the initialization. Better to do what @BoP mentioned -- declare a vector, and add elements to an empty vector.allSignChangeEdges = new IndexAndSign[2]{{1,false},{2,true}};just works. So the question remains, how do you want to initialize them?