How can we use constructor to initialize array of object. For example we have:
class K{
K(int i){}
};
int main(){
K* k = new K[10];
}
It makes compile error. How to deal with it?
Since the only applicable constructor of class K is the one taking an int the compiler cannot default-construct the elements in your newly allocated array, which is what it tries (and fails) in the following:
K * k = new K[10]; // 1. allocate memory for 10 elements
// 2. default these 10 elements them
The above would work if K had a default-constructor, ie. if it was defined as:
class K {
K() { /* ... */ } // <- default constructor
K(int i) { /* ... */ }
/* ... */
};
You have to explicitly initialize each and every element of the array using something as the below:
K * k = new K[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // C++11
Note: if you don't have the pleasure of working in C++11 you cannot use the above solution, and solutions where braced-initialization isn't available quickly becomes a mess.. easiest solution in that case is to add a default-constructor to K, or to use a std::vector and add one K element at a time (or using the copy-constructor of K.