5

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?

stardt
  • 1,179
  • 1
  • 9
  • 14
  • 1
    In C++ arrays require constant expressions for their size. i.e. it must be a compile-time constant, but N in your example is initialized dynamically though to a literal. – Khaled Alshaya Mar 13 '12 at 16:43
  • Note that `gcc` actually support variable length arrays in C++ as an extension you just [can't initialize them like that](http://stackoverflow.com/a/27339171/1708801) – Shafik Yaghmour Mar 21 '15 at 03:53

2 Answers2

9

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.

Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
  • The C++ compiler looks not smart enough to me though, many other main stream languages can support initializing an array in the ints[N] way. – Zhile Zou Apr 23 '14 at 12:56
3

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Is there any way to create a variable array? I need it to hold X number of ints, depending on what the user enters, I have no way of knowing what they will enter so it *has* to be variable. – MarcusJ May 29 '14 at 06:13