14

I am trying to implement a stack using an array but I receive an error.

class Stack{
private:
    int cap;
    int elements[this->cap]; // <--- Errors here
    int top;
public:
  Stack(){
     this->cap=5;
     this->top=-1;
};

The indicated line has these errors:

Multiple markers at this line
- invalid use of 'this' at top level
- array bound is not an integer constant before ']' token

What am I doing wrong?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
user1849859
  • 319
  • 1
  • 3
  • 16

3 Answers3

29

In C++, the size of an array must be a constant known at compile-time. You'll get an error if that isn't the case.

Here, you have

int elements[this->cap];

Notice that this->cap isn't a constant known at compile-time, since it depends on how big cap is.

If you want to have a variably-sized array whose size is determined later on, consider using std::vector, which can be resized at runtime.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
2

You cannot use this in the declaration like that. this is a constant pointer passed to non-static methods in your class. It does not exist outside of that scope.

Such array declarations need constant values/expressions for the size. You don't want that, you want a dynamicly sized container. The solution is to use a std::vector.

user123
  • 8,970
  • 2
  • 31
  • 52
0

Since other have already explained the cause of this issue, here is a possible solution to resolve it. Since it seems you may not know the array size at compile time and the assignment may restrict the use of std::vector<int> consider using a pointer implementation.

#include <algorithm>

class Stack{
private:
    int cap;
    int* elements; // use a pointer
    int top;
public:
    Stack(){
        this->cap=5;
        this->top=-1;
        elements = new int[this->cap];
    }

    Stack(const Stack& s) 
         : cap(s.cap) , top(s.top), elements(NULL)
    {
         if(cap > 0) {
             elements = new int[cap];
         }

         std::copy(s.elements , s.elements + cap, elements );
    }

    Stack& operator=(Stack s) {
         swap(s, *this);
         return  *this;
    }

    ~Stack() {delete [] elements;}

    friend void swap(Stack& first, Stack& second)
    {
        using std::swap; 
        swap(first.top, second.top);
        swap(first.cap, second.cap);
        swap(first.elements, second.elements);
    }
};
andre
  • 7,018
  • 4
  • 43
  • 75
  • I don't really know how to implement copy constructor and operator==. Could you help me? – user1849859 May 08 '13 at 20:29
  • @user1849859 Added. Read up on the [c++ copy-swap-idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) to fully understand why we have to implement all of this If we use a dynamic array. – andre May 08 '13 at 20:48