I have the following class in C++:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const
?
This doesn't work:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
Edit: The case in point is when I can have different values for b
for different instances, but the values are known to be constant for the lifetime of the instance.
Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
With C++11 the answer to this question has now changed and you can in fact do:
std::vector
uses the heap. Geez, what a waste that would be just for the sake of aconst
sanity-check. The point ofstd::vector
is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.ConstFixedSizeArrayFiller
andConstFixedSizeArray
are reusable.The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become
const
after this initialization.The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.
b_filler
is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.
It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).
A solution without using the heap with
std::vector
is to useboost::array
, though you can't initialize array members directly in the constructor.