title: Downcasting best-practice (C++)
body: <p>Static code analysis tools tend to ramble a lot about "downcasting a base class to a derived class" and I also found a couple of coding standard guides, which mention not to do this so I was wondering what is the best-practice way.</p>
  
  <p>Here's my use case:</p>
  
  <p>I have a Base (interface), DerivedA, DerivedB classes and then an array containing Base pointers.</p>
  
  <p>Then I iterate through the array and based on a flag, I determine if the object is DerivedA or DerivedB, cast it down and do some random stuff to the object from the outside.</p>
  
  <p>Basically something like this:</p>
  
  <pre><code>// arr is of type Base**
  for (int i = 0; i &lt; size; ++i)
  {
      // doMagic has an overload for both types
      if (arr[i]-&gt;isDerivedA())
      {
          doMagic(reinterpret_cast&lt;DerivedA*&gt;(arr[i]));
      }     
      else if (arr[i]-&gt;isDerivedB())
      {
          doMagic(reinterpret_cast&lt;DerivedB*&gt;(arr[i]));
      }
  }
  </code></pre>
  
  <p>Bout the reinterpret, I cannot use dynamic_cast due to embedded platform restrictions (the same for C++11), but the Base class being an interface guarantees that the object is either DerivedA or DerivedB.</p>
  
  <p>I could make DerivedA and DerivedB only implement pure virtual calls, thus i wouldn't have to worry about downcasting anything, but the DerivedA and DerivedB classes are very much specialized and doMagic does completely different things with the instances...</p>
  
  <p>So I was wondering how you guys approach this - having a single array of very different objects, but inherited from a single base, iterating through them and doing some specialized stuff from the outside.</p>