How to initialize an array of class elements in the constructor?

I am trying to do the following:

class sig { public: int p_list[4]; } sig :: sig() { p_list[4] = {A, B, C, D}; } 

I get an error

missing expression in constructor.

So how do I initialize an array?

+8
source share
6 answers

Only in C ++ 11:

 class sig { int p_list[4]; sig() : p_list { 1, 2, 3, 4 } { } }; 

Pre-11, it was not possible to initialize arrays other than automatic and static in the block area or static in the namespace area.

+18
source

So how do I initialize an array?

Using normal initializer list syntax:

 sig::sig() : p_list{1, 2, 3, 4} { } 

Please note: this only works in C ++ 11. Before that, you need to use boost::array to initialize it inside the function.

+8
source

If your compiler does not support C ++ 11 initialization, you need to assign each field separately:

 p_list[0] = A; p_list[1] = B; p_list[2] = C; p_list[3] = D; 
+4
source

If your current compiler does not yet support C ++ 11, you can initialize the contents of the vector using standard algorithms and functors:

 class sig { public: sig() { struct Functor { Functor() : value(0) {}; int operator ()() { return value++; }; int value; }; std::generate(p_list, p_list + 4, Functor()); } int p_list[4]; }; 

The previous example snippet is here .

Yes, it's pretty ugly (at least it looks ugly for me) and doesn't do the work at compile time; but it does the work you need in the constructor.

If you need some other initialization (initialization with even / odd numbers, initialization with random values, beginning with anoter value, etc.), you only need to change the functor, and this is the only advantage of this ugly approach.

+2
source

You can initialize array elements like this using the C ++ 11 compiler, using the -std = C ++ 11 or -std = gnu ++ 11 option

 struct student { private : int marks[5]; public : char name[30]; int rollno; student(int arr[], const char *name, int rno):marks{arr[0], arr[1], arr[2], arr[3], arr[4]}{ strcpy(this->name, name); this->rollno = rno; } void printInfo() { cout <<"Name : "<<this->name<<endl; cout <<"Roll No : "<<this->rollno<<endl; for(int i=0; i< 5; i++ ) { cout <<"marks : "<<marks[i]<<endl; } } }; int main(int argc, char *argv[]) { int arr[] = {40,50,55,60,46}; //this dynamic array passing is possible in c++11 so use option -std=c++11 struct student s1(new int[5]{40, 50, 55, 60, 46}, "Mayur", 56); //can't access the private variable //cout <<"Mark1 : "<<s1.marks[0]<<endl; s1.printInfo();`enter code here` } 
+1
source
 p_list[4] = {'A', 'B', 'C', 'D'}; 
-3
source

All Articles