'error: invalid use of non-static data member

class Stack
{               
private:

    int tos;
    const int max = 10;    
    int a[max];
public:

    void push(int adddata);
    void pop();
    void printlist();
};

error: invalid use of non-static data member 'max'

whats wrong in the code, and please help me with proper correction. Thankyou



Solution 1:[1]

It is mandatory that the array size be known during compile time for non-heap allocation (not using new to allocate memory).

If you are using C++11, constexpr is a good keyword to know, which is specifically designed for this purpose. [Edit: As pointed out by @bornfree in comments, it still needs to be static]

static constexpr int max = 10;

So, use static to make it a compile time constant as others have pointed out.

Solution 2:[2]

As the error says, max is a non-static member of Stack; so you can only access it as part of a Stack object. You are trying to access it as if it were a static member, which exists independently of any objects.

Hence you need to make it static.

static const int max = 10;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.

Solution 3:[3]

As the compiler says make the data member static

static const int max = 10;    

Solution 4:[4]

You need to make max a compile time constant:

static const int max = 10;

Solution 5:[5]

The Conceptual mistake that you are making is that you are trying to initialize values for the class in the class definition .This is the reason why constructors exist .Using a parametrized constructor set values of top of stack and its size. When making the stack object pass the size of the stack to be created:

class Stack {               
private:
  int tos; 
  int a[max];

public:
  Stack(int s);
  void push(int adddata);
  void pop();
  void printlist();
};

Stack::Stack(int s) {
  tos=-1;
  max=s;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Vlad from Moscow
Solution 4 Johan Lundberg
Solution 5 gudok