title: C++ polymorphism - Auto detect derived type
body: <p>I have certain code that I want to optimize. It looks like this:</p>
  
  <pre><code>function abc( string format ) {
    if (format == "a") { // this is a string, I shouldn't have used single quote, sorry for the confusion
      classx::a t;
      doit(t);
    }
    if (format == "b"){
      classx::b t;
      doit(t);
    }
    if (format == "c"){
      classx::c t;
      doit(t) 
    }
    if (format == "d"){
      classx::d t; 
      doit(t);
    }
  }
  </code></pre>
  
  <p>Currently there is many doit() function with different type</p>
  
  <pre><code>function doit( classx:a ) {
     different code for a
  }
  
  function doit( classx:b ) {
     different code for b
  }
  </code></pre>
  
  <p>...etc</p>
  
  <p>As you can see, a lot of code is replicated. However I can't figure out how to reduce the words.
  Note that :
  doit(x) has overloaded by different type.
  a,b,c,d class is derived from a class named "X". </p>
  
  <p>I may create a pointer type classx::X :</p>
  
  <pre><code>classx::X *t;
  if (format == "a") t = new classx::a
  if (format == "b") t = new classx::b
  if (format == "c") t = new classx::c
  if (format == "d") t = new classx::d
  doit(*t)
  </code></pre>
  
  <p>but then still need to write a doit() for type classx::X with a bunch of "if then" and cast to the correct type... as C++ can't auto-detect and cast to correct type.</p>
  
  <p>I wonder if there is a faster/smarter way to do this. 
  Thanks in advance.</p>