Is there a way to work around this?Im declaring class objects in a switch statement and later using that variable outside the switch, it only works if i put the rest of my code in each case which isnt very efficient.Heres my code
switch (shape)
{
case 'q':
{
Quad geo(a,b,c,d);
}
break;
case 'r':
{
Rectangle geo(a,b,c,d);
}
break;
case 't':
{
Trapezoid geo(a,b,c,d);
}
break;
case 'p':
{
Parrelogram geo(a,b,c,d);
}
break;
case 's':
{
Square geo(a,b,c,d);
}
break;
default:
break;
}
geo.print();//obviously wont work
Have an
IPrintableinterface, like thisThen, derive your types
Quad,Rectangle, etc fromIPrintable, i.e. implement that interface. Then your code looks like this:Of course, if the common functionality is more than print, you can add those functions to the interface as well. Also take a look at the visitor pattern. It may or may not be of help to you depending on the specifics of your problem.