title: Trouble with understanding virtual functions
body: <pre><code>#include&lt;iostream&gt;
  
  using namespace std;
  
  class X
  {
      int a;
      int b;
      public:
      void f(int a)
      {
          cout&lt;&lt;"\nInside X";
      }
  
  
      virtual void abc ()
      {
          cout&lt;&lt;"\nHello X";
      }
  
  };
  
  
  class Y : public X
  {
      int a;
      public:
  
      void f(int a, int b)
      {
          cout&lt;&lt;"\nInside Y";
      }
  
  
      void abc()
      {
          cout&lt;&lt;"\nHello Y";
      }
  
  };
  
  
  
  int main()
  {
  
      X a;
  
      cout&lt;&lt;sizeof(X);
  
      Y b;
  
      cout&lt;&lt;sizeof(Y);
  
      X *h = new Y;
  
      h-&gt;abc();
  }
  </code></pre>
  
  <p>I understand that the reason the size of class X is 12 bytes, is because it contains a vptr (virtual pointer) to the virtual table. Is there anyway I could read this virtual table and if not, could at least access the virtual pointer. I tried using unions, but it gave me some kind of error.</p>
  
  <p>Also, when I call h->abc() , how does it know the object of class, <code>h</code> is pointing to? I thought most of this was done at compile time. But when you have a base class pointer pointing to a derived class, how does it know which class function to execute.
  Consider these two situations</p>
  
  <pre><code>X *h = new X;
  h-&gt;abc();/* This would call the abc function in X */
  </code></pre>
  
  <p>and</p>
  
  <pre><code>X *h = new Y;
  h-&gt;abc();/* This would call the abc function in Y*/
  </code></pre>
  
  <p>I read, that the <code>h</code> pointer would go to the vtable of the object it is pointing to and would hence call that function? But how is this achieved in runtime?</p>