I need to be able to retrieve a type based on an ID.
To achieve this, I am intending to create a base class for the types, which declares all the functions as pure virtual functions.
class Base
{
public:
virtual int function1() = 0;
virtual int function2() = 0;
};
I then create derived classes, instantiate these and store the pointers to the instances in an std::unordered_map
of base pointers.
std::unordered_map<int, Base*> types;
Each element of the std::unordered_map
will point to a different derived class type (i.e. no duplicates).
Then I can retrieve the type I need by getting the associated member from the std::unordered_map
.
Base* ptr = types[4];
// Use type...
int num = ptr->function1();
Now I know this could come down to opinion, but is this a horrible use of C++? Is there a cleaner way to do this?
Update
I could use instance of the derived classes instead of their respective IDs, however I would likely have to dynamically allocate each one on the heap (i.e. using new
), and I am going to be creating a lot of these, so the overhead from dynamic allocation could have an unwanted effect on performance.