How to Initialize an Array

How to Initialize an Array

How do you initialize or assign values to an array in a class?

The short answer is that you can’t initialize an array member as you would initialize a scalar data member. You can use memset to zero all the elements of the array inside the constructor’s body or use a loop that assigns values to each array element.

class A{ private:  int ar[10]; public: A()  {   for (int i=0; i

In most cases, it's best to use a vector object instead of a built-in array, thereby avoiding the initialization problem right from the start:

class A{private:std::vector  vi;//instead of array//...};


Share the Post: