Ahmed Mohamed
Ahmed Mohamed

Reputation: 51

declare a constant variable in a struct causes me this error a nonstatic member reference must be relative to a specific object

Hallo I am trying to declare an array in a struct and when I declare the size as a constant variable it shows me this error

a nonstatic member reference must be relative to a specific object

and if I declare the constant variable out of the struct scope the error goes away.

here is my code:

  struct Student{

      string name;
      string birthday;
      int studyYear;
      string Faculty;
      string Department;
      const int MaxNrOfCrs = 10;  // here is my error 
      const int Grade = 1;        // The same error appears here also
      Course crs[MaxNrOfCrs][Grade];
      bool payment;
  };

but when I try to take the two constants out of the struct Student scope the error does not appear any more

  const int MaxNrOfCrs = 10;  // The error vanishes here
  const int Grade = 1;        // The same error vanishes here also

  struct Student{

      string name;
      string birthday;
      int studyYear;
      string Faculty;
      string Department;
      Course crs[MaxNrOfCrs][Grade];
      bool payment;
  };

Upvotes: 1

Views: 90

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

Even though a class member is declared const with a default value, it can still be constructed in each individual instance of the class with some different value, via a constructor or, as in this case, aggregate initialization, perhaps.

Temporarily removing the invalid array declaration, here's some valid C++:

#include <string>
using namespace std;

struct Student{

      string name;
      string birthday;
      int studyYear;
      string Faculty;
      string Department;
      const int MaxNrOfCrs = 10;  // here is my error 
      const int Grade = 1;        // The same error appears here also
      bool payment;
};

Student s{"John", "1/1/2000", 2017, "Engineering", "Mechanical",
    20, 5, true};

So, this ends up constructing a class instance with MaxNrOfCrs containing 20.

So, what do you propose the size of your class array member to be here? It can't be different for every instance of the class, obviously.

Here, a const only means that this class member is constant after an instance of this class is constructed. And it can be constructed with any value, therefore you can't really use this class member to specify the immutable size of an array (there are a few other reasons too).

In the other case, you declared a global const int. End of story. Nothing could possibly change that. Hence you can use it to specify the size of some array.

Upvotes: 3

Related Questions