title: Static cast base to derived pointer and construct derived members
body: <p>A minimal example of what I want: I have two classes</p>
  
  <pre><code>template&lt;typename T&gt;
  struct General;
  
  template&lt;typename T&gt;
  struct Specific;
  </code></pre>
  
  <p>with <code>Specific</code> inheriting from <code>General</code>, but <code>General</code> calling a <code>Specific</code> member function in its constructor:</p>
  
  <pre><code>template&lt;typename T&gt;
  struct Specific: public General&lt;T&gt; {
      int y;
      void compute() { 
          y=x;
          this-&gt;x++; 
      }
  };
  
  template&lt;typename T&gt;
  struct General {
      int x;
      General(int x) : x(x) { static_cast&lt;Specific&lt;T&gt;*&gt;(this)-&gt;compute(); };
  };
  </code></pre>
  
  <p>The idea is that there is one General class and multiple specific ones, and which one to use is decided either at run time or compile time. </p>
  
  <p>The code above compiles and runs correctly, even though <code>y</code> is never actually constructed. I think I get away with it because it's a primitive type, but if I use a more complicated <code>y</code> instead:</p>
  
  <pre><code>template&lt;typename T&gt;
  struct Specific: public General&lt;T&gt; {
      std::vector&lt;int&gt; y;
      void compute() { 
          y={0}; //anything here
          this-&gt;x++; 
      }
  };
  </code></pre>
  
  <p>then the code still compiles, but when executing the line with the comment I get a read access violation error because <code>y</code> hasn't been constructed.</p>
  
  <p>There is a way out of it, and that's to have the variable y in <code>General</code> as opposed to <code>Specific</code>. This works, but different implementations need different variables, and it's not very elegant to include lots of protected variables in <code>General</code> that are only used by one implementation each (although from a performance standpoint, I guess compilers remove unused member variables as long as that can be detected in compile-time correct?). So is there a better way to do it?</p>
  
  <p>Edit: One possible way suggested by Scheff:</p>
  
  <pre><code>General(int x) : x(x) { 
      Specific&lt;T&gt; B;
      B = static_cast&lt;Specific&lt;T&gt;&amp;&gt;(*this);
      B.compute();
      *this = static_cast&lt;General&lt;T&gt;&amp;&gt;(B);
  }
  </code></pre>