title: in C++, why compiler does not understand which object is pointed by base class object at compile time?
body: <p>in C++, why compiler does not understand which object is pointed by base class object at compile time?</p>
  
  <p>For ex. </p>
  
  <pre><code>int Add(int nX, int nY)
  {
      return nX + nY;
  }
  int Subtract(int nX, int nY)
  {
      return nX - nY;
  }
  
  int main()
  {
      // Create a function pointer and make it point to the Add function
      int (*pFcn)(int, int) = Add;
      cout &lt;&lt; pFcn(5, 3) &lt;&lt; endl; // add 5 + 3
      pFcn = Subtract;
      cout&lt;&lt; pFcn(5,3)&lt;&lt;endl // pefrom 5-3
      return 0;
  }
  </code></pre>
  
  <p>Above code snippet is the example of Late binding or Dynamic binding.</p>
  
  <p>In above example, at compile time only we came to know that 1st Add function is going to call through pFcn &amp; then Subtract function is going to call. Then why it is called to be example of Dynamic binding even though compiler knows which function to call at compile time only?</p>
  
  <hr>
  
  <p>my question is regarding to virtual function also. consider following ex, </p>
  
  <pre><code>class Base {
  public:
      void NonVirtual() {
          cout &lt;&lt; "Base NonVirtual called.\n";
      }
      virtual void Virtual() {
          cout &lt;&lt; "Base Virtual called.\n";
      }
  };
  class Derived : public Base {
  public:
      void NonVirtual() {
          cout &lt;&lt; "Derived NonVirtual called.\n";
      }
      void Virtual() {
          cout &lt;&lt; "Derived Virtual called.\n";
      }
  };
  int main() {
      Base* bBase = new Base();
      Base* bDerived = new Derived();
  
      bBase-&gt;NonVirtual();
      bBase-&gt;Virtual();
      bDerived-&gt;NonVirtual();
      bDerived-&gt;Virtual();
  }                                               
  </code></pre>
  
  <p>Here dynamic binding is happening. Which function to invoked is decided at run-time. So here why compiler can not decide at compile time only which function to invoke? </p>