2

Hi I'' trying to make a template for a class to print out values in an array.

#include<iostream>
using namespace std;

template <typename T>
class Array{
   public:
      Array(T array[], int arraysize){
         size=arraysize;
         _array=new T[size];
      }

      ~Array(){
         delete[] _array;
      }
      void print(){
         for(int i=0; i<size; i++){
            cout<<_array[i]<<' ';
         }
      }
      private:
         T *_array;
         int size;
};

int main(){
   int array1[5]={1,2,3,4,5};
   Array<int> a(array1,5);
   a.print();

   float array2[5]={1.012, 2.324, 3.141, 4.221, 5.327};
   Array<float> b(array2,5);
   b.print();

   string array3[]={"Ch1","Ch2","Ch3","Ch4","Ch5"};
   Array<string> c(array3,5);
   c.print();

   return 0;

}

This is the code and I was wondering what's wrong because it would print out random numbers.

Jenny Choi
  • 37
  • 1
  • 5

2 Answers2

2

The code creates the template's class member _array using new, but does not initialize it to anything, and that's why you get random garbage printed out.

The constructor does receive a parameter array, and an initialized array is passed using that parameter. However, that parameter is completely ignored by the constructor, and nothing is done with it.

Your intent here, obviously, is to copy the contents of the array the template constructor receives, as an argument, into _array. But that code is missing.

The contents of the array parameter will not get copied into _array all by themselves. You have to write the code to do that.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
2

Your constructor:

Array(T array[], int arraysize){
     size=arraysize;
     _array=new T[size];
}

All you did was to assign the Array's size and allocate memory without actually copying the contents. So all you see some random value for POD types, and default-constructed values for class types.

You should do the copying with std::copy

Array(T array[], int arraysize) 
     : _array(new T[arraysize]), size(arraysize)
{
    std::copy(array, array+arraysize, _array);
}

As you can see, I used member initailizer list; Please remember the Rule of 5. Also, I advise you to use a std::unique_ptr instead.

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68