Since others have already explained the cause of this problem, here is a possible solution to solve it. Since it seems you do not know the size of the array at compile time, and the purpose may limit the use of std::vector<int> consideration of the use of the 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 source share