my code has 3 classes n_hexa,n_octa,n_bin. The code is here
switch(choice)
{
case 1: cin>>n;
n_hexa nx(n);
break;
case 2: cin>>n;
n_octa no(n);
break;
case 3: cin>>n;
n_bin nb(n);
break;
}
on compiling it gives a message "crosses initialisation of n_hexa" for line of n_octa
The variable can be declared, but it cannot be initialized.
Can i create object inside switch case in C++ ?? Yes you can, but you should probably assign it to an object (or object pointer) of the same type that already exists outside of the switch block, unless you won't need to use it outside of the switch block.
Syntax of switch...caseIf there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2 , statements after case constant2: are executed until break is encountered. If there is no match, the default statements are executed.
A Switch is made up of a bunch of Cases and one will fire that matches a condition. The order technically does not matter.
If you want to have temporary objects inside a case, you'll need to scope them properly.
switch(choice)
{
case 1:
{
cin>>n;
n_hexa nx(n);
break;
}
case 2:
{
cin>>n;
n_octa no(n);
break;
}
case 3:
{
cin>>n;
n_bin nb(n);
break;
}
}
Try declaring the variables above the switch command:
n_hexa nx;
n_octa no;
n_bin nb;
switch(choice) {
case 1:
cin>>n;
nx(n);
break;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With