c++arrayscompiler-errors

error: invalid use of non-static data member


class Stack
{               
private:

    int tos;
    const int max = 10;//here it gives an error    
    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

  • 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.