1

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.