Home > Software engineering >  Stuck using an array in the constructor as a parameter
Stuck using an array in the constructor as a parameter

Time:04-18

I am new to this and I am having a problem. I want to use an array as a parameter in the constructor, but when I want to initialize the parameter in the main() function and call the class, it seems I can't directly put the array values as I did with the name and surname. The simplified code looks like below. It shows an error that the default constructor is not available.

class Student {
private:
    string name;
    string surname;
    int age;
    int grade[5];
public:
    Student(string e, string b, int c,int A[5]) {
        name = e;
        surname = b;
        age = c;
        for (int i = 0; i < 5; i  )
            grade[i] = A[i];

    }
};

int main() {
    Student obj = Student("Jack","blalba", 18, {10,10,9,8,8});
}

CodePudding user response:

The only thing that needs to be changed is the constructor:

Student(string e, string b, int c, int (&&A)[5]) {
        name = e;
        surname = b;
        age = c;
        for (int i = 0; i < 5; i  )
            grade[i] = A[i];
    }

CodePudding user response:

     Student(string e, string b, int c,int A[5])

There's no such thing as a function, method, or a constructor parameter that's an array. Array cannot be functions parameters, C simply does not work this way.

You can write such a declaration, but what happens is that the parameter gets converted to a pointer. The above declaration is logically equivalent to:

     Student(string e, string b, int c,int *A)

And now the reason for your compilation error is very obvious:

Student obj = Student("Jack","blalba", 18, {10,10,9,8,8});

The expression {10, 10, 9, 8, 8} cannot be converted to an int * in C .

The simplest solution is to pass it explicitly as an array:

int a[5]={10,10,9,8,8};
Student obj = Student("Jack","blalba", 18, a);

It should also be possible to use a std::initializer_list, but that would be more complicated than needed.

  • Related