title: Why is the function call to the virtual function using the address stored in the virtual method table returning garbage?
body: <p>I'm calling virtual functions from the address in the virtual table as an exercise to test my understanding of the concept. However, as soon as I thought I made a breakthrough in my understanding of the virtual method table, I run into another issue that I just don't understand. </p>
  
  <p>In the code below, I've created a class called <code>Car</code> which contains a member variable x and two virtual functions, first and second. Now, I call these two virtual methods by hacking through the virtual table. The first function returns the correct answer, but the second returns some random value or garbage instead of what it was initialized to be. </p>
  
  <pre><code>#include &lt;cstdio&gt;
  
  class Car
  {
  private:
      int x;
  
      virtual int first()
      {
          printf("IT WORKS!!\n");
          int num = 5;
          return num;
      }
      virtual int second()
      {
          printf("IT WORKS 2!!\n");
          //int num  = 5;
          return x;
      }
  
  
  public:
  
      Car(){
          x = 2;
      }
  };
  
  int main()
  {
      Car car;
      void* carPtr = &amp;car;
      long **mVtable =(long **)(carPtr);
  
      printf("VTable: %p\n", *mVtable);
      printf("First Entry of VTable: %p\n", (void*) mVtable[0][0]);
      printf("Second Entry of VTable: %p\n", (void*) mVtable[0][1]);
  
      if(sizeof(void*) == 8){
          printf("64 bit\n");
      }
  
      int (*firstfunc)() = (int (*)()) mVtable[0][0];
      int x = firstfunc();    
  
      int (*secondfunc)() = (int (*)()) mVtable[0][1];
      int x2 = secondfunc();
  
      printf("first: %d\nsecond: %d", x, x2);
      return 0;
  }
  </code></pre>
  
  <p>If someone can point me to what I'm doing wrong that would be appreciated. Also, since this works differently across compilers, I'm testing it on <a href="http://cpp.sh/" rel="nofollow noreferrer">http://cpp.sh/</a> using c++14. </p>
  
  <p>That code out outputs, where the "garbage" second output is subject to change:</p>
  
  <pre><code>VTable: 0x400890
  First Entry of VTable: 0x400740
  Second Entry of VTable: 0x400720
  64 bit
  IT WORKS!!
  IT WORKS 2!!
  first: 5
  second: -888586240 
  </code></pre>