![]() |
|
[C] Create object instance based on enumeration value - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C] Create object instance based on enumeration value (/showthread.php?tid=5835428) |
Create object instance based on enumeration value - chrizator - May 11, 2018 Hey folks, quick question. Let's assume I have an Enum called 'AnimalType'. And a lot of animals inheriting from a base 'Animal' class (class Dog : public Animal). Now, based on what 'AnimalType' I have, I want to create the corresponding derivation. Let's assume (IDK if the shit below compiles, just writing it in HF editor): Code enum class AnimalTypeI'd like to have a method that does the following: Code Animal* getAnimalFromEnum(AnimalType type)The code above will probably work, but I find it kind of silly. Especially when working with A LOT of Enum values, this is gonna get ugly. I'd like to have a method using unordered map or something similiar. I don't know how to achieve that. Still new to C++. Thanks for taking the time! 🤝 RE: Create object instance based on enumeration value - Annabelle Lee - May 11, 2018 Using an unordered map, you can do something like this... Code #include <iostream>RE: Create object instance based on enumeration value - Gorzoid - May 11, 2018 (May 11, 2018 02:46 PM)Annabelle Lee Wrote: Using an unordered map, you can do something like this... +1 unique_ptr, +1 for at(), -1 no virtual destructor doesn't affect your code, but probably would in OP's case OP, it's pretty much either this or a switch statement, you just gotta pick your poison since there is no runtime reflection of types in C++ RE: Create object instance based on enumeration value - Annabelle Lee - May 11, 2018 (May 11, 2018 04:37 PM)Gorzoid Wrote: +1 unique_ptr, +1 for at(), -1 no virtual destructor doesn't affect your code, but probably would in OP's case Virtual destructor was left out on purpose, since I simply wanted to illustrate the point. Also recently discovered unique_ptr/make_unique and smart pointers, so I've been having a field day playing with them. RE: Create object instance based on enumeration value - 6577657534735 - May 11, 2018 switch case is better than a map because with all warnings enabled the compiler will warn you if you add a new enum but forget to define a new creation method |