Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using delete in overloaded = in derived class

Tags:

c++

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.

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

class baseDMA
{
private:
   char * label;

...
};

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

Now when overloading the = operator, we delete the label pointer 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)

This is the overloaded = operator for the base class:

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

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

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);
}

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

hasDMA & hasDMA::operator=(const hasDMA & hs)
{
    if (this == &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;
} 

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

Thanks in advance

like image 494
Kakalokia Avatar asked Sep 01 '26 00:09

Kakalokia


1 Answers

The reason is because the author made a mistake. This is an excellent example of how you should not ever manage your own memory- he should be using std::vector to manage his memory. He didn't, and as a result, his code was very wrong, and that's exactly the way your code is going to go if you imitate him.

In addition, he uses the seriously outdated self-assignment-check no-longer-an-idiom, and no copy-and-swap.

In short, get a new book. This is all bad.

like image 174
Puppy Avatar answered Sep 03 '26 14:09

Puppy