0

Code below produces this error:

class HASHTABLE
{
public:
  const int DIMENSION = 10;
  struct NODE
  {
     char* INFO;
     NODE* LINK;
  };
  NODE arr1[DIMENSION];
};


int main()
{
  const int dimension=10;
  struct node
  {
    char* info;
    node* link;
  };
  node arr2[dimension];
};

So, code in int main() gives no errors, but code in class HASHTABLE when i declare NODE arr1[DIMENSION]; I get error: int(10) a nonstatic member reference must be relative to specific object.

The solution is obvious, just put static const int DIMENSION = 10; and I get no errors.

But for how much I understand C++, this code in main and in class are the same.

Can someone explain what happens behind the scene?

Also, I hope I understand this:

If I declare DIMENSION as a static, every object I create using HASHTABLE will have also the same DIMENSION, but I thought that was secured via using const?

kvantour
  • 25,269
  • 4
  • 47
  • 72

1 Answers1

1

But for how much i understand c++, this code in main and in class are same.

they are different. for class case, if you don't add static, every instance of HASHTABLE has it's own DIMENSION.

I found const static is required if you want to do this inside class. I guess the compile error is because of the compiler can't determine the value of DIMENSION if DIMENSION is not declared as static.

i tought that was secured via using const

const is to prevent the variable from being written. But static in class is to declare a shared variable between instances.

Andy Chang
  • 69
  • 3
  • Hello and thank you for your answer. But i just dont understand why it needed to be `static`? It was already const, so every instance of HASHTABLE would have its DIMENSION=10. I realy think word `static` is unnecessary, or im missing something? – Nikola Bozin Sep 14 '18 at 13:13
  • [here](https://stackoverflow.com/questions/13662441/c11-allows-in-class-initialization-of-non-static-and-non-const-members-what-c) shows some restrictions of class member initialization. probably it's the cause. – Andy Chang Sep 14 '18 at 13:50