Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize a const array in a class initializer in C++

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 image 571
Nathan Fellman Avatar asked Oct 02 '08 11:10

Nathan Fellman


People also ask

How do you initialize a const member of a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Can const be initialized in constructor?

A constructor can initialize an object that has been declared as const , volatile or const volatile .

Do const variables need to be initialized?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .

Can arrays be const?

Arrays are Not Constants The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.


1 Answers

With C++11 the answer to this question has now changed and you can in fact do:

struct a {     const int b[2];     // other bits follow      // and here's the constructor     a(); };  a::a() :     b{2,3} {      // other constructor work }  int main() {  a a; } 
like image 77
Flexo Avatar answered Sep 22 '22 15:09

Flexo