I undestand that objects instantiated inside of a switch case or an if condition will cease to exist once that block of code has been left (as explained in this question). But what is then the right way to instantiate an object depending on e.g. user input? I believe one can see from the example what I'm (clumsily) trying to do:
class triangle
{
public:
static const int dimension = 2;
};
class tetrahedron
{
public:
static const int dimension = 3;
};
template<class T>
class element
{
public:
int getDimension()
{
return T::dimension;
}
};
int main()
{
int elementType;
std::cout<< "Enter 1 for triangle or 2 for tet: "
std::cin >> elementType;
switch(elementType)
{
case 1:
{
element<triangle> myElementFile;
break;
}
case 2:
{
element<tetrahedron> myElementFile;
break;
}
}
// I want to use myElementFile further, but it does not exist here
std::cout<< "The dimension is: " << myElementFile.getDimension(); //this won't work
return 0;
}
I don't know if the overall approach of using classes as "containers" for storing info about the different elements and then feeding them into a different class is optimal, but I should stick to it for now, because I was told to. :) I am new to c++ and OOP in general. Thank you for any tips!