user3584564
user3584564

Reputation: 180

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

Upvotes: 12

Views: 36463

Answers (5)

Titus
Titus

Reputation: 927

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.

Upvotes: 13

Anchellon
Anchellon

Reputation: 9

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

Upvotes: 0

Vinay Shukla
Vinay Shukla

Reputation: 1844

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.

Upvotes: 5

Johan Lundberg
Johan Lundberg

Reputation: 27038

You need to make max a compile time constant:

static const int max = 10;

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

As the compiler says make the data member static

static const int max = 10;    

Upvotes: 1

Related Questions