title: Getting std::type_index of derived class from within base constructor in C++17?
body: <p>Please consider the following C++17 program:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;optional&gt;
  #include &lt;typeindex&gt;
  
  std::optional&lt;std::type_index&gt; b, d;
  
  struct B {
    B() { b = std::type_index(typeid(*this)); }
  
    virtual ~B() = default;
  };
  
  struct D : B {
    D() { d = std::type_index(typeid(*this)); }
  };
  
  int main() {
    D x;
    if (b.value() == d.value())
      std::cout &lt;&lt; &quot;EQ&quot; &lt;&lt; std::endl;
    else
      std::cout &lt;&lt; &quot;NE&quot; &lt;&lt; std::endl;
  }
  </code></pre>
  <p>It outputs <code>NE</code>.</p>
  <p>So it seems that during construction of the base class typeid returns the info about B and not D.</p>
  <p>That is by design, right?  (Why was it designed this way?  The implementation knows at runtime what derived class it is constructing that B is a base class subobject of doesn't it?)</p>
  <p>Is there any way to get the type_index of the derived class from within the constructor of B?</p>