title: C++ - Change the type of an object
body: <p><strong>In brief:</strong></p>
  
  <p>Is it possible to change the type of an object once established?</p>
  
  <p><strong>What I've tried:</strong></p>
  
  <p>For instance given the design:
  (edit: To clarify, this is a simplified example of a strategy design pattern, it isn't important what <code>ChangeData</code> does, only that we can change what it does by changing <code>_interface</code>)</p>
  
  <pre><code>struct MyClass
  {
      int _data;
      MyInterface* _interface;
  
      void DoChangeData() { Interface-&gt;ChangeData(*this); }
  };
  
  MyClass x;
  x._interface = new DerivedClass1();
  x.DoChangeData(); // do something
  x._interface = new DerivedClass2();
  x.DoChangeData(); // do something else
  </code></pre>
  
  <p>switching <code>_interface</code> allows us to change the operations upon the class, however this necessitates creating wrapper methods (<code>DoChangeData</code>) and always passing the <code>this</code> pointer as an argument, which is ugly.</p>
  
  <p>A better solution I would prefer is:</p>
  
  <pre><code>struct MyClass abstract
  {
      int _data;
  
      virtual void ChangeData() = 0;
  };
  </code></pre>
  
  <p>But here once the concrete class is established, unlike <code>_interface</code>, it cannot be changed. It seems like this should be possible providing the different derived classes don't add any new fields. Is there any way to implement the <code>ChangeClass</code> function below?</p>
  
  <pre><code>DerivedClass1 x;
  x.DoChangeData(); // do something
  x.ChangeClass(DerivedClass2); // ???
  x.DoChangeData(); // do something else
  </code></pre>
  
  <p>Note I am talking about virtual classes, and <code>reinterpret_cast</code> only works with non-virtual objects. Copy constructors require the overhead of moving existing memory, which I would also rather avoid.</p>