0

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?

Vlad from Moscow
313k27 gold badges204 silver badges358 bronze badges
asked Mar 16, 2014 at 22:31

2 Answers 2

3

For example

K* k = new K[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

provided that your compiler supports this feature of the C++ 2011.

answered Mar 16, 2014 at 22:33
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Mar 16, 2014 at 22:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.