Reputation: 6488
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 the constructor.
So how do I initilalise an array?
Upvotes: 9
Views: 44187
Reputation: 31
You can initialise the array members like this using c++11 compiler using -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`
}
Upvotes: 1
Reputation: 13320
If your current compiler doesn't yet support C++11, you can initialize the vector contents 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];
};
Previous snippet example here.
Yes, is kind of ugly (at least, it looks ugly for me) and doesn't do the work at compile time; but it does the work that you need in the constructor.
If you need some other kind of initialization (initialization with even/odd numbers, initialization with random values, start with anoter value, etc...) you only need to change the Functor, and this is the only advantage of this ugly approach.
Upvotes: 2
Reputation: 545518
So how do I initilalise an array?
Using the normal initialiser list syntax:
sig::sig() : p_list{1, 2, 3, 4}
{ }
Note, this only works in C++11. Before that, you need to use a boost::array
an initialise it inside a function.
Upvotes: 8
Reputation: 409136
If your compiler doesn't support C++11 initialization, then you have to assign each field separatly:
p_list[0] = A;
p_list[1] = B;
p_list[2] = C;
p_list[3] = D;
Upvotes: 5
Reputation: 476950
In C++11 only:
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 ones at block scope or static ones at namespace scope.
Upvotes: 19