Trying to use a switch to choose which to declare

I'm not sure if this is possible, but what I am trying to do is use a switch to decide what type a variable should be (i have 3 classes to choose from)
it says its not being declared, so is that because the sections of a switch are like functions and everything declared inside goes away when that part does?
if so, is it possible to use pointers to choose?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
	switch( number ) {
		case 1:
			firstClass *variableName;
			variableName = new firstClass;
			break;
		case 2:
			secondClass *variableName;
			variableName = new secondClass;
			break;
		case 3:
			thirdClass *variableName;
			variableName = new thirdClass;
			break;
	}


thanks in advance
Last edited on
Variables only exist in the scope that they are declared.
So after the break; variableName no longer exists.

You need to have a parent child relationship and declare through polymorphism.

e.g.
1
2
3
4
5
6
7
8
9
parent *parentobj = 0;
switch(number) {
 case 1:
  parent = new child1();
  break;
 case2:
  parent = new child2();
  break;
}


Then using overloaded methods you can achieve the functionality you need.

hey thanks a lot, its working :D
Topic archived. No new replies allowed.