Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 831
user3584564 Avatar asked Apr 19 '15 18:04

user3584564


3 Answers

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.

like image 176
Titus Avatar answered Sep 17 '22 15:09

Titus


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.

like image 28
Vinay Shukla Avatar answered Sep 18 '22 15:09

Vinay Shukla


As the compiler says make the data member static

static const int max = 10;    
like image 41
Vlad from Moscow Avatar answered Sep 20 '22 15:09

Vlad from Moscow