Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why i cant instantiate objects inside a switch-case block

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

like image 300
lovesh Avatar asked Dec 09 '10 05:12

lovesh


People also ask

Can a variable be initialized in switch case?

The variable can be declared, but it cannot be initialized.

Can switch case create object?

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.

How do you use a switch case inside a function?

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.

Can switch cases be out of order?

A Switch is made up of a bunch of Cases and one will fire that matches a condition. The order technically does not matter.


2 Answers

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;
    }
}
like image 145
EboMike Avatar answered Sep 20 '22 20:09

EboMike


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;
...
like image 21
Shadow Wizard Hates Omicron Avatar answered Sep 19 '22 20:09

Shadow Wizard Hates Omicron