I have a base class [for example]:

class base
    std::string name;

    virtual void set_name(const std::string& name) = 0;
    virtual std::string get_name() const = 0;
  • And 20 class inherited from it.
  • And I have a UI (build with Qt) which user can select type of class to create it.

for handle this i use enumeration type [for example]:

enum class types

and i end up with a long switch-case for type creation [for example]:

case types::TYPE_1:
    return std::make_shared<type_1>();
case types::TYPE_2:
    return std::make_shared<type_2>();

i think you can imagine the ugly code in other section of code which depend of type of objects.

How could i make it cleaner ?

  • You have received a number of downvotes and the likely reason is that you are asking for the "best" way to do something and how to make the solution "cleaner". Both these words are only likely to result in opinions. People often downvote without providing any feedback. Your question is currently too broad to be answered well. Instead, you may wish to retract your question and then ask it again with more specific details about what you are attempting to achieve. – Jason K. Jun 17 at 15:59

For creating the objects, you could make a factory object, but in the end that's still going to have the same switch statement you currently have, just in a different object. Swings and roundabouts.

However, that's not going to fix this:

i think you can imagine the ugly code in other section of code which depend of type of objects.

I can imagine what happens if everywhere you use one of these objects you've got to have a switch statement or similar based on the type of the object. What that says to me is that you've got a bigger problem with your design in that you're passing around what is (effectively) an empty object and then subverting the type system to work out what object type it actually is. I don't think we can fix that for you without more details as to why you think you need to do this rather than just passing round more specific types.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.