using delete in overloaded = in derived class
<p>I was reading through Chapter 13 of the C++ Primer Plus book.
It had an example that dealt with using inheritance with dynamic memory allocation, copy constructors and overloading the = operator.</p>

<p>The base class, which is called <code>baseDMA</code> has a private pointer-to-char that uses <code>new</code> in the constructor.</p>

<pre><code>class baseDMA
{
private:
   char * label;

...
};

baseDMA::baseDMA(const char * l)
{
    label = new char[std::strlen(l) + 1];
    std::strcpy(label, l);
    ...
}
</code></pre>

<p>Now when overloading the <code>=</code> operator, we delete the <code>label pointer</code> because we will be assigning it to a new value and it will point to a new location. If we don't delete it then we will not be able to do so later because the pointer will point to something different now and the old location that was pointed to by this pointer is not deleted and also has nothing pointed to it now (this is how the author explains it in a different chapter)</p>

<p>This is the overloaded <code>=</code> operator for the base class:</p>

<pre><code>baseDMA &amp; baseDMA::operator=(const baseDMA &amp; rs)
{
   if (this == &amp;rs)
      return *this;
   delete [] label;
   label = new char[std::strlen(rs.label) + 1];
   std::strcpy(label, rs.label);
   return *this;
}
</code></pre>

<p>Next the author defines a derived class called hasDMA, which also uses <code>new</code> for a <code>pointer-to-char</code> that he he defines as the following:</p>

<pre><code>class hasDMA :public baseDMA
{
private:
    char * style;
    ...
};

hasDMA::hasDMA(const char * s, const char * l)
: baseDMA(l)
{
    style = new char[std::strlen(s) + 1];
    std::strcpy(style, s);
}
</code></pre>

<p>Now the part the confuses me a little, is that when the author overloads the <code>=</code> operator for the derived class, he doesn't seem to <code>delete [] style</code> before giving it a new value, just as he did with <code>label</code> from the base class. This is how the author did the overloaded <code>=</code> operator for the derived class:</p>

<pre><code>hasDMA &amp; hasDMA::operator=(const hasDMA &amp; hs)
{
    if (this == &amp;hs)
       return *this;
    baseDMA::operator=(hs); // copy base portion
    //no delete [] style
    style = new char[std::strlen(hs.style) + 1];
    std::strcpy(style, hs.style);
    return *this;
} 
</code></pre>

<p>What is the reason for not freeing the memory pointed to by <code>style</code> just as we freed the memory pointed to by <code>label</code> from the base class before assigning it a new value?</p>

<p>Thanks in advance</p>
