11
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

5 Answers 5

13

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.

2
  • 7
    Even in c++11, I think you can't just use constexpr. You will have to use static constexpr int max = 10.
    – bornfree
    Commented Jan 27, 2019 at 8:25
  • Non-static data members cannot be constexpr. The comment above is correct. Commented Mar 3, 2022 at 10:18
5

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.

1

As the compiler says make the data member static

static const int max = 10;    
1

You need to make max a compile time constant:

static const int max = 10;
3
  • Not all compilers support that, it will have to be made static const int max; in header and const int Stack::max = 10; in the cpp file
    – tejas
    Commented Apr 19, 2015 at 18:42
  • @tejashs: the definition of max has to appear in the header too.
    – user1084944
    Commented Apr 19, 2015 at 18:54
  • If you have a bad/old compiler you can also go and do inline static const int max(){return 10; } Commented Apr 19, 2015 at 18:54
0

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.