You're attempting to use a C idiom, where the last member of a structure is a very short array (one or, if permitted by the compiler as a nonstandard extension, zero elements) and extra memory is allocated for the structure so elements beyond the end of the declared array can be accessed. This was originally a nonstandard trick, known as the struct hack, or in some compilers as zero-length arrays. It was standardized in C99 as flexible arrays.
When you used this idiom, you needed to allocate additional memory for the array, e.g. sizeof (struct Array) + sizeof (int) * number_of_elements
. Otherwise you wouldn't have memory allocated for more elements than you actually declared (usually one or zero), and you'd get undefined behaviour when you tried to access elements beyond that.
However, you're writing C++, not C99. Even if your compiler allows you to do this, relying on it would be very bad practice, and a lot more awkward C++ than in C.
Either store a pointer in the class and allocate the appropriate amount of memory in the constructor, and deallocate it in the destructor, or use a C++ class that will manage the memory for you, e.g. std::vector
.
Here's an example of using std::vector
:
#include <vector>
class Array{
public:
int size;
int range;
std::vector<int> array;
Array(int size, int range) :
size( size ),
range( range ),
array( size, 0 )
{
}
};