user1376415
user1376415

Reputation: 69

C++ variable array as class member

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?

Upvotes: 6

Views: 39839

Answers (3)

Ahmed Jolani
Ahmed Jolani

Reputation: 3072

Let's go through the complete reason behind this, first of all when you declare a class initially, any member variable has not been allocated any memory, so public or private methods have no value. That was a quick tip for you, now for your problem:

You can't do that outside the class since any array size should be known before the compilation because any statically declared array resides in the function's stack frame, and the compiler needs to know how much memory to allocate exactly. The only segment in memory that is resized by the programmer is the heap. So, whenever you want to have a dynamically allocated array size, you need to declare it to reside in the heap, and you do that like so:

int a;
cin >> a;
int * b = new int[a];

That's the correct way to declare an array with an unknown size (size determined during the runtime), to integrate this with your class here is how you do it, and recall that any class private or public attributes have no memory - They are just declarations that should not contain any initialization somewhere else in the member methods or outside the class - this is because they are public, as in your case - and of course after declaring an instance of the class e.g Test t. Anyway, here is how you do it within the class:

class Test
{
public:
int a;
int * b;
Test(int Ia=1) {
    a = Ia;
    b = new int[a];
}
~Test() {
    delete[] b;
}
};

See delete vs delete[] operators in C++ for why to use delete[] instead of delete in the destructor.

Upvotes: 5

demi
demi

Reputation: 5504

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;
};

Upvotes: 12

Nicol Bolas
Nicol Bolas

Reputation: 473427

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.

Upvotes: 6

Related Questions