title: How does delete know the size of derived class from base pointer?
body: <p>I am curious how the delete operator know the size of the derived class when calling delete on base pointer, here is a minimal example:</p>
  
  <pre><code>class IVariant
  {
  public:
      virtual ~IVariant() = default;
      virtual void print_value() = 0;
  };
  
  template&lt;typename T&gt;
  class Variant: public IVariant {};
  
  template&lt;&gt;
  class Variant&lt;int&gt;: public IVariant
  {
  private:
      int m_integer;
  
  public:
      Variant(int integer): m_integer(integer) {}
      void print_value() override
      {
          printf("integer: %i\n", m_integer);
      }
  };
  
  template&lt;&gt;
  class Variant&lt;double&gt;: public IVariant
  {
  private:
      double m_dbl;
  
  public:
      Variant(double val): m_dbl(val) {}
      void print_value() override
      {
          printf("double: %g\n", m_dbl);
      }
  };
  
  template&lt;&gt;
  class Variant&lt;std::string&gt;: public IVariant
  {
  private:
      std::string m_string;
  
  public:
      Variant(const std::string&amp; string): m_string(string) {}
      void print_value() override
      {
          printf("string: %s\n", m_string.c_str());
      }
  };
  </code></pre>
  
  <p>Test:</p>
  
  <pre><code>int main()
  {
      IVariant* int_var = new Variant&lt;int&gt;(100);
      IVariant* dbl_var = new Variant&lt;double&gt;(100.0f);
      IVariant* str_var = new Variant&lt;std::string&gt;("the value is 100\n");
  
      int_var-&gt;print_value();
      dbl_var-&gt;print_value();
      str_var-&gt;print_value();
  
      delete int_var;
      delete dbl_var;
      delete str_var;
  }
  </code></pre>
  
  <p>The delete operator correctly knew from the base pointer alone that <code>int_var = variant&lt;int&gt;</code> so freed 4 bytes, <code>dbl_var = variant&lt;double&gt;</code> so freed 8 bytes, <code>str_var = variant&lt;std::string&gt;</code> so it freed 28 bytes.</p>
  
  <p>But how does it know? Does the new operator store size &amp; pointer which the delete operator can then use to free the correct number of bytes? I know this is how delete[] works for arrays but I was unable to find any info when it came to derived classes</p>