Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variable array as class member

Tags:

c++

arrays

I have a small C++ program defined below:

class Test
{
   public:
   int a;
   int b[a];
};

When compiling, it produces an error:

testClass.C:7:5: error: invalid use of non-static data member ‘Test::a’
testClass.C:8:7: error: from this location
testClass.C:8:8: error: array bound is not an integer constant before ‘]’ token

How do I learn about what the error message means, and how do I fix it?

like image 844
user1376415 Avatar asked Nov 29 '22 17:11

user1376415


2 Answers

You cannot use an array with undefined size in compile time. There are two ways: define a as static const int a = 100; and forget about dynamic size or use std::vector, which is safer than the manual memory management:

class Test
{
public:
  Test(int Num)
    : a(Num)
    , b(Num) // Here Num items are allocated
  {
  }
  int a;
  std::vector<int> b;
};
like image 104
demi Avatar answered Dec 01 '22 07:12

demi


Unless you dynamically allocate them (such as with new[]), arrays in C++ must have a compile-time constant as a size. And Test::a is not a compile-time constant; it's a member variable.

like image 22
Nicol Bolas Avatar answered Dec 01 '22 07:12

Nicol Bolas