title: Pure Virtual Function call from Base Ctor
body: <p>Consider the following sample code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  class base
  {
     public:
        base()
        {
           bar(); //Line1
           this-&gt;bar(); //Line2
           base *bptr = this; 
           bptr-&gt;bar(); //Line3
           ((base*)(this))-&gt;bar(); //Line4
        }
  
        virtual void bar() = 0;
  };
  
  class derived: base
  {
     public:
        void bar()
        {
           cout &lt;&lt; "vfunc in derived class\n";
        }
  };
  
  int main()
  {
     derived d;
  }
  </code></pre>
  
  <p>The above code has pure virtual function <code>bar()</code> in base class which is overriden in the derived class. The pure virtual function <code>bar()</code> has no definition in base class.</p>
  
  <p>Now focus on <code>Line1</code>, <code>Line2</code>, <code>Line3</code> and <code>Line4</code>.</p>
  
  <p><strong>I understand</strong> : <code>Line1</code> gives compilation error, because pure virtual function cannot be called from ctor.</p>
  
  <p><strong>Questions:</strong></p>
  
  <ol>
  <li><p>Why does <code>Line2</code> and <code>Line4</code> give no <code>compilation error</code> for the same reason mentioned in <code>I understand</code> statement above?. The calls in <code>Line2</code> and <code>Line4</code> will eventually cause <code>linker-error</code> only.</p></li>
  <li><p>Why does <code>Line3</code> give neither compilation error nor linker error but gives <code>run-time exception</code> only ?</p></li>
  </ol>
  
  <p>Real-Life example of UB when Pure virtual function call through constructor:</p>
  
  <p><img src="https://i.stack.imgur.com/gWeqe.png" alt="Real-Life example of UB when Pure virtual function call through constructor"></p>