I have just found out that the following is not valid.
//Header File class test { const static char array[] = { '1', '2', '3' }; };
Where is the best place to initialize this?
You can't do it; the size of the array needs to be specified in the class declaration. If you want something variable-sized, use a vector. If you require dynamically sized arrays you should read into dynamic memory allocation with C++.
The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.
Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.
The best place would be in a source file
// Header file class test { const static char array[]; }; // Source file const char test::array[] = {'1','2','3'};
You can initialize integer types in the class declaration like you tried to do; all other types have to be initialized outside the class declaration, and only once.
You can always do the following:
class test { static const char array(int index) { static const char a[] = {'1','2','3'}; return a[index]; } };
A couple nice things about this paradigm:
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