How to initialise a member array of class in the constructor?

Viewed 41537

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?

6 Answers

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`
} 
Related