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 cod
Have an IPrintable
interface, like this
struct IPrintable
{
virtual ~IPrintable() {}
virtual void Print() = 0;
};
Then, derive your types Quad
, Rectangle
, etc from IPrintable
, i.e. implement that interface. Then your code looks like this:
std::unique_ptr pShape;
switch(shape)
{
case quad:
pShape.reset(new Quad(...));
case rect
pShape.reset(new Rect(...));
}
if(pShape)
pShape->Print();
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.