Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable-sized object may not be initialized

Tags:

c++

arrays

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?

like image 767
stardt Avatar asked Mar 13 '12 16:03

stardt


2 Answers

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.

like image 116
Ferdinand Beyer Avatar answered Oct 21 '22 18:10

Ferdinand Beyer


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 ints.

like image 22
Robᵩ Avatar answered Oct 21 '22 16:10

Robᵩ