title: Type Confusion in C++
body: <p>I am referring to this <a href="https://bufferoverflows.net/type-confusion-vulnerabilities/" rel="nofollow noreferrer">link</a>.</p>
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  
  class Base {}; // Parent Class
  
  class Execute: public Base {   // Child of Base Class
  public:
      virtual void exec(const char *program) 
      {
          system(program);
      }
  };
  
  class Greeter: public Base {   // Child of Base Class
  public:
      virtual void sayHi(const char *str) 
      {
          cout &lt;&lt; str &lt;&lt; endl;
      }
  
  };
  
  
  int main() {
  
      Base *b1 = new Greeter();
      Base *b2 = new Execute();
      Greeter *g;
  
      g = static_cast&lt;Greeter*&gt;(b1); // Safe Casting to the same type &quot;Greeter&quot;
      g-&gt;sayHi(&quot;Greeter says hi!&quot;); // String passed to sayHi() function
  
      g = static_cast&lt;Greeter*&gt;(b2); // Unsafe Casting to sibling class &quot;Execute&quot;
      g-&gt;sayHi(&quot;/usr/bin/xcalc&quot;); // String passed to exec() function 
                                      // which will turn into a command to execute calculator
  
      delete b1;
      delete b2;
      return 0;
  }
  </code></pre>
  <p>My question is about the statements:</p>
  <pre><code>g = static_cast&lt;Greeter*&gt;(b2);
  g-&gt;sayHi(&quot;/usr/bin/xcalc&quot;);
  </code></pre>
  <p><code>b2</code> is an instance of type <code>Execute</code>. The b2 instance will have a vpointer to vtable containing entry for <code>exec()</code>. When the next statement calls <code>g-&gt;sayHi(..)</code>, how will the vtable be used to look up which function to call ?</p>
  <p>Referring to <a href="https://pabloariasal.github.io/2017/06/10/understanding-virtual-tables/" rel="nofollow noreferrer">link</a>, it states that:</p>
  <blockquote>
  <p>the function name is used as index to the vtable to find the correct
  (most specific) routine to be executed</p>
  </blockquote>
  <p>If the name of the function is used, then how is the name <code>sayHi</code> found in the vtable for type <code>Execute</code> ?</p>