Hello guys, I'm a bit stuck on this one. I am getting an error (error C2360: initialization of 'student1' is skipped by 'case' label) if I don't declare and initialize the pointer on the same line it compiles and works. Like this (EnglishStudent *student1; then on line 2 *student1 = new EnglishStudent)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int type = whatStudent();
switch (type)
{
case 1:
EnglishStudent *student1 = new EnglishStudent();
student1->Calculate();
break;
case 2:
MathStudent *student2 = new MathStudent();
student2->Calculate();
break;
case 3:
ScienceStudent *student3 = new ScienceStudent();
student3->Calculate();
break;
}
No it is language rules. You are not allowed to jump over variable declaration. Brackets introduce new scope which ends before next case begins, so you are not jumping over anything.
No it is language rules. You are not allowed to jump over variable declaration. Brackets introduce new scope which ends before next case begins, so you are not jumping over anything.
Thanks for the clarification. But if I understood it right, the solution I gave does fix it or?
Hey guys thanks yes the brackets fixed it works now. Also sorry for the mistake :) Like this (EnglishStudent *student1; then on line 2 *student1 = new EnglishStudent)
case 1:
EnglishStudent *student1 = new EnglishStudent(); //Student 1 initialisation
student1->Calculate();
break;
case 2: //Jumping over it
//You are able to use student1 here (as it in same scope), but what it will equals to?
//What if it was a more complex type you cannot use uninitialized?
//To avoid those problems jumping over variable initialization was prohibited
1 2 3 4 5 6 7 8 9
case 1:
{ //A new scope is created
EnglishStudent *student1 = new EnglishStudent(); //Student 1 initialisation
student1->Calculate();
break;
} //student1 is destroyed here.
case 2:
//you have no access to student1 (in fact it is not even exist now)
//So this is safe
If you declare (initialize) your variable before swithc then there is no danger too: initialization already happened
YOu can use brackets if it works for you. Just do not forget to delete object when you done. OP code have leaks everywhere.
If all those students are subclasses of some GenericStudent with proper virtual functions (because it does look as inheritance exercise), code can be rewritten as:
1 2 3 4 5 6 7 8 9
GenericStudent* student = nullptr;
int type = whatStudent();
switch (type) {
case 1: student = new EnglishStudent(); break;
case 2: student = new MathStudent(); break;
case 3: student = new ScienceStudent(); break;
}
student->Calculate();
delete student;