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.