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.
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:
I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:
however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.
ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:
Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:
The output being:
Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:
How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:
Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.
If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.