title: Calling pure virtual function
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors">Calling virtual functions inside constructors</a>  </p>
  </blockquote>
  
  
  
  <p>Look at this code.
  In the constructor of Base class, we can call the pure virtual function using 'this' pointer. Now when I want to create a typed pointer to the same class and casting 'this' to the same type. It throws run time exception 'pure virtual function call exception'. Why is this so ?</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  class Base
  {
    private:
    virtual void foo() = 0;
    public:
    Base()
    {
      //Uncomment below 2 lines and it doesn't work (run time exception)
      //Base * bptr = (Base*)this;
      //bptr-&gt;foo();
      //This call works
      this-&gt;foo();
    }
  };
  
  void
  Base::foo()
  {
    cout &lt;&lt; "Base::foo()=0" &lt;&lt; endl;
  }
  
  class Der : public Base
  {
    public:
    Der()
    {
    }
    public:
    void foo()
    {
      cout &lt;&lt; "Der::foo()" &lt;&lt; endl;
    }
  };
  
  int main()
  {
    cout &lt;&lt; "Hello World!" &lt;&lt; endl;
    Der d;
  }
  </code></pre>