Search code examples
c++arraysinitializationfill

C++ Pointer of Array of Ints Initialization


I want to have an array accessible by all functions of a class.

I put the array as private variable in the header file.

    private:
    int* arrayName;

In the .cpp file where I implement the class, the constructor takes in an int value (size) and creates the array. The goal is to fill it up

ClassName::ClassName(int numElements){
  arrayName = new int[numElements]; //make arrays the size of numElements
  for(int i = 0; i<numElements; i++)
      arrayName[i] = 0;
}

I feel like this is quite inefficient. I know you can do int array[5] = {0}; but how do you do it when you don't initially know the size.


Solution

  • If you want to zero-initialize a newed array, just do value-initialize it. This has the effect of zero-initializing its elements:

    arrayName = new int[numElements]();
    //                              ^^
    

    But you really want to be using an std::vector<int>.

    private:
      std::vector<int> vname;
    

    and

    ClassName::ClassName(int numElements) : vname(numElements) {}
    

    This way you don't have to worry about deleting an array and implementing copy constructors and assignment operators.