Consider the following class:
class A {
const int arr[2];
public:
A() { }
};
Is it possible to initialize arr
from the constructor initializer list or in any other way than on the line where it is declared (i.e. const int arr[2] = {1,2};
)?
Note that I'm interested in methods that work with C++98!
Initializing array elements to non-zero values requires C++11 support.
In C++03, it's only possible to value-initialize your array, resulting in each element's value being
0
:For the relevant C++03 standardese, see this question and answer:
How can i use member initialization list to initialize it?
(I'm going to assume that by C++98 you mean not C++11, i.e. that C++03 is acceptable. If this assumption is wrong, please say so.)
By wrapping them in a
struct
, e.g.:This does mean that to access the data, you'd have to write
arr.arr
. It's possible to avoid that by inheriting from thestruct
:This does make the name of the
struct
visible outside of the class (which might be an advantage—client code could pass you one as an argument).If you don't have an instance of the struct handy, say because you want to fill it with values calculated from arguments to the constructor, you can use a static member function:
For the OP’s concrete example:
No. It's not.