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;
};
The testing code is
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 the 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 the line with int nums[N]
I don't get a compilation error, so the similar code for the ints
array is fine. Isn't the value of N
known at compile time?
What's going on? Why is nums
considered a variable-sized array? Why are the arrays nums
and ints
handled differently?
Isn't the value of
N
known at compile time?
No. At the time aMemberFunction
is compiled, the compiler does not now what N
is, since its value is determined at run-time. It is not smart enough to see that there is only one constructor, and assumes that the value of N
could be different than 5.
N
isn't known at compile time in your example, but it is in this one:
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 will declare a local array of five int
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With