Stack

Hello.

I am trying to create a stack program in c++.

I created class as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class MyStack{

      public:
             int size;
             int top;;
    
             MyStack();
             MyStack(int x, int y) : size(x), top(-1){};
             ~MyStack(){};

             int stack[size];
             void push(int x);
             int pop();
             void display();
      };


I am getting error : " invalid use of non-static data member `MyStack::size' "

I don't want to make size as static as i want every instance of this class to set it's own size of stack.

Thanks for your help in advance.

Regards,
Sunil
You are trying to declare array of int's based on the size variable which is not known at the compile time. You should never use non-constant variable to declare an array. If you do want to declare an array based on size variable, you should do something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

class MyStack { 

      public:
          int size ;
          int *arr; 
          
          MyStack(int s = 10) {
                 arr    = NULL ; 
                 size   = s       ; 
                 if (size != 0) { 
                     arr = new int[size] ; 
                 } 
          } 
         ~MyStack() { 
                if (arr != NULL) { 
                      delete [] arr ; 
                } 
          }               
          
} ; 


Hope this helps !
Topic archived. No new replies allowed.