title: Best practices for run-time polymorphism for Embedded C++? ROMable run-time polymorphism?
body: <p>I require run-time polymorphism in my embedded c++ project. In my research on best practices for embedded c++ I have found that it is recommended that objects be declared in static memory and to avoid dynamic allocation (new/delete/malloc/free) as much as possible if not entirely.</p>
  
  <p>Below is what I have come up with for run-time polymorphism in embedded C++. The idea is that you dynamically allocate the InterfaceA object, use it immediately and then delete it. You do not hold any instances of that interface class. Any persistent data would be picked up ( e.g. get_index() ) from the interface class and stored externally. Anytime you need to operate with interface functions, you re-allocate the interface, use it immediately and delete it. This would avoid using the heap as much as possible.</p>
  
  <p>This seems not fully optimal. Since I am not storing any static data within the interface I hope there is a way for me to use the interface statically.</p>
  
  <p><strong>What is the best way to do run-time polymorphism while avoiding dynamic allocation?</strong></p>
  
  <p><strong>Bonus: Is there any way to do run-time polymorphism while keeping the application (mostly) ROMable?</strong></p>
  
  <pre><code>class A
  {
      public:
          int index;
          int init(int type);
  }
  
  int A::init(int type)
  {
      Interface* interface = SelectInterface(type);
      index = interface-&gt;get_index(type);
      delete interface;
  }
  </code></pre>
  
  <p>And then I have the following interface:</p>
  
  <pre><code>// ----------- INTERFACES -------------- //
  
  class Interface
  {
      virtual int get_index() = 0;
  }
  
  // This is the interface factory
  Interface* SelectInterface(int type)
  {
      if (type == 0)
      { 
          return new InterfaceA();
      }
      else if (type == 1)
      {
          return new InterfaceB();
      }
  
      return null;
  }
  
  class InterfaceA :: public Interface
  {
      InterfaceA();
      int get_index();
  } 
  
  int InterfaceA::get_index()
  {
      return 5;
  }
  
  class InterfaceB :: public Interface
  {
      InterfaceB();
      int get_index();
  } 
  
  int InterfaceB::get_index()
  {
      return 6;
  }
  </code></pre>