-4

I want to initialize each element of the array through the constructor

    const int size=5;
Student students[size];
students[0]=("Sarah",96,92,90); <---- the error is here

constructor

Student(string sn,double m1,double m2,double fin)
{
    studentName=sn;
    midterm1Grade=m1;
    midterm2Grade=m2;
    finalExamGrade=fin;
}

it shows me an error with the way I am intializing

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

3

Your syntax is wrong. C++ doesn't recognise a random parenthesised, comma-delimited list of things, because it doesn't know that you intend that list to be a list of arguments to the Student constructor.

Instead, you must create a temporary, un-named object of type Student and assign it:

const unsigned int SIZE = 5;

Student students[SIZE];
students[0] = Student("Sarah", 96, 92, 90);
//            ^^^^^^^

Note, though, that this is not initialisation. It's merely after-the-fact assignment. Because of this, your compiler will require Student to have a default constructor (one that takes no arguments), because it will require it for the initial creation of the SIZE elements, on the line Student students[SIZE].

To initialise, perhaps you can do something like this:

Student students[] = {
   { "Sarah", 96, 92, 90 },
   { "Bob",   80, 72, 54 },
   // ...
};

Notice how we no longer need the constant named SIZE: when we initialise like this, the initialiser knows how many elements there are going to be, so the array length can be automatically determined.

You may still want to keep SIZE for use elsewhere, though, in which case I'd recommend putting it back into the array declaration so that if the initialiser list length is at odds with this size then you will get a pleasing compiler error.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3
    const int size=5;
Student students[size] = { { "Sarah",96,92,90 }, { /*initializer list for index 1 }, ...{ /*initializer list for index 4 } };
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Your construction happened at the line below

Student students[size]

Digital_Reality
  • 4,488
  • 1
  • 29
  • 31