title: How does the C++ delete operator find the memory location of a polymorphic object?
body: <p>I would like to know how the delete operator figures out the memory location that needs to be freed when it is given a base class pointer that is different from the true memory location of the object.</p>
  
  <p>I want to duplicate this behavior in my own custom allocator/deallocator.</p>
  
  <p>Consider the following hierarchy:</p>
  
  <pre><code>struct A
  {
      unsigned a;
      virtual ~A() { }
  };
  
  struct B
  {
      unsigned b;
      virtual ~B() { }
  };
  
  struct C : public A, public B
  {
      unsigned c;
  };
  </code></pre>
  
  <p>I want to allocate an object of type C and delete it through a pointer of type B. As far as I can tell this is a valid use of operator delete, and it works under Linux/GCC:</p>
  
  <pre><code>C* c = new C;
  B* b = c;
  
  delete b;
  </code></pre>
  
  <p>The interesting thing is that the pointers 'b' and 'c' actually point to different addresses because of how the object is laid out in memory, and the delete operator "knows" how to find and free the correct memory location.</p>
  
  <p>I know that, in general, it is not possible to find the size of a polymorphic object given a base class pointer: <a href="https://stackoverflow.com/questions/8122763/find-out-the-size-of-a-polymorphic-object">Find out the size of a polymorphic object</a>. I suspect that it is not generally possible to find the true memory location of the object either.</p>
  
  <p>Notes:</p>
  
  <ul>
  <li>My question is not related to how new[] and delete[] work. I am interested in the single object allocation case. <a href="https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array">How does delete[] &quot;know&quot; the size of the operand array?</a>.</li>
  <li>I am not concerned about how the destructor is called either. I am interested in the deallocation of the memory itself. <a href="https://stackoverflow.com/questions/10229481/how-delete-works-when-i-delete-a-pointer-of-base-class">How &#39;delete&#39; works when I delete a pointer of base class</a></li>
  <li>I tested using -fno-rtti and -fno-exceptions, so G++ should not have access to runtime type information.</li>
  </ul>