A variable-sized object cannot be initialized.

I have a class like this

class aClass { public: aClass() : N(5) {} void aMemberFunction() { int nums[N] = {1,2,3,4,5}; } private: const int N; }; 

Test code

 int main() { aClass A; A.aMemberFunction(); const int N = 5; int ints[N] = {5,4,3,2,1}; return 0; } 

When I compile (g ++ 4.6.2 20111027), I get an error

 problem.h: In member function 'void aClass::aMemberFunction()': problem.h:7:31: error: variable-sized object 'nums' may not be initialized 

If I comment out a line using int nums[N] , I don't get a compilation error, so similar code for ints array ints good. Is the value of N known at compile time?

What's happening? Why is nums considered an array of variable size? Why are nums and ints arrays handled differently?

+5
source share
2 answers

Is the value of N known at compile time?

Not. At compile time aMemberFunction compiler now has no value N , since its value is determined at runtime. It is not smart enough to see that there is only one constructor, and suggests that the value of N may differ from 5.

+9
source

N not known at compile time in your example, but it is in this:

 class aClass { private: static const int N = 5; public: aClass() {} void aMemberFunction() { int nums[N] = {1,2,3,4,5}; } }; 

The above code will compile and declare a local array of five int s.

+3
source

Source: https://habr.com/ru/post/913073/


All Articles