In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?
class Class { public: int array[]; Class(int x) : ??? { } }
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.
If no default constructor is defined for the class, the initializer list must be complete, that is, there must be one initializer for each element in the array. The first element of aPoint is constructed using the constructor Point( int, int ) ; the remaining two elements are constructed using the default constructor.
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.
You folks have so overcomplicated this. Of course you can do this in C++. It is fine for him to use a normal array for efficiency. A vector only makes sense if he doesn't know the final size of the array ahead of time, i.e., it needs to grow over time.
If you can know the array size one level higher in the chain, a templated class is the easiest, because there's no dynamic allocation and no chance of memory leaks:
template < int ARRAY_LEN > // you can even set to a default value here of C++'11 class MyClass { int array[ARRAY_LEN]; // Don't need to alloc or dealloc in structure! Works like you imagine! } // Then you set the length of each object where you declare the object, e.g. MyClass<1024> instance; // But only works for constant values, i.e. known to compiler
If you can't know the length at the place you declare the object, or if you want to reuse the same object with different lengths, or you must accept an unknown length, then you need to allocate it in your constructor and free it in your destructor... (and in theory always check to make sure it worked...)
class MyClass { int *array; MyClass(int len) { array = calloc(sizeof(int), len); assert(array); } ~MyClass() { free(array); array = NULL; } // DON'T FORGET TO FREE UP SPACE! }
You can't initialize the size of an array with a non-const dimension that can't be calculated at compile time (at least not in current C++ standard, AFAIK).
I recommend using std::vector<int>
instead of array. It provides array like syntax for most of the operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With