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
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.
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.
As the compiler says make the data member static
static const int max = 10;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With