Reputation: 105
when I am doing this switch statement I am getting this error:error: ‘Ptr’ was not declared in this scope. I do not understand why this is happening since I am dynamically allocating Ptr. If I remove the curly braces I get the error: ‘Ptr’ has a previous declaration as ‘(//Class Name)* Ptr’. How do I fix this? Thanks.
switch(i){
case 0:{
Class0* Ptr = new Class0;
}
case 1:{
Class1* Ptr = new Class1;
break;
}
case 2:{
Class2* Ptr = new Class2;
break;
}
case 3:{
Class3* Ptr = new Class3;
break;
}
case 4:{
Class4* Ptr = new Class4;
break;
}
case 5:{
Class5* Ptr = new Class5;
break;
}
}
myMap["key"] = Ptr;
Upvotes: 0
Views: 2815
Reputation: 1666
This is a common scoping error
{
int j =1;
}
cout<<j<<endl;
The value of j is only accessible inside the brackets and not outside it i.e. the cout statement will give an error. You can use the following workaround for your task.
switch(i){
case 0:{
Class0* Ptr = new Class0;
myMap["key"] = Ptr;
break;
}
case 1:{
Class1* Ptr = new Class1;
myMap["key"] = Ptr;
break;
}
case 2:{
Class2* Ptr = new Class2; myMap["key"] = Ptr;
break;
}
case 3:{
Class3* Ptr = new Class3; myMap["key"] = Ptr;
break;
}
case 4:{
Class4* Ptr = new Class4; myMap["key"] = Ptr;
break;
}
case 5:{
Class5* Ptr = new Class5; myMap["key"] = Ptr;
break;
}
}
Upvotes: 1