Question

I'm trying to compile the next code, but I'm getting this error on the indicated line

"Invalid types `int[int]' for array subscript "

Code:

template<typename T>
class Stack {
      private:
              static const int GROW_FACTOR = 2;
              static const int START_LENGHT = 10;

              T * data;
              int max;
              int used;

              void allocateIfNeeded() {
                   if (used == max) {
                      T * aux = new T[max*GROW_FACTOR];
                      for (int i=0; i<max; i++) {
                          aux[i] = data[i];
                      }
                      max *= GROW_FACTOR;
                      delete[] data;
                      data = aux;
                   }
              }
      public:
             Stack() {    
                 max = START_LENGHT;
                 data = new T[max];
                 used = 0;
             }

             void push(T data) {
                 allocateIfNeeded();
                 data[used++] = data; // <-- compile error
             }

             T pop() {
                 return data[--used];
             }

             T top() {
                 return data[used-1];
             }

             bool isEmpty() {
                  return used == 0;
             }           
};

I have checked for other situations when this error msg show up, but I think they have nothing to do with this.

Was it helpful?

Solution

The parameter name data is hiding the object member name data within the scope of the function. To refer to it you have to explicitly qualify it with this->data:

        void push(T data) {
             allocateIfNeeded();
             this->data[used++] = data; // <-- compile error
         }

Alternatively use some sort of identifier naming scheme (such as prefixing members with 'm_') that results in name parameters not having the same name as members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top