Assignment Operator

The same concern about shallow versus deep copy also applies to the assignment operator. In this case, however, there is an additional complication. Suppose you initialized two Employee objects, fred and wilma:

   Employee fred, wilma;
   // other work here
   fred = wilma;

You want to assign to fred's member variables all the values in wilma (with a deep, not a shallow copy). However, what happens to fred's existing values? They must be deleted, especially if they are pointers, or you will create a memory leak. Thus, before doing the deep copy assignments, you must first delete any pointers already in use by fred:

 Employee & Employee::operator=(const Employee & rhs)
 {
   delete pEmpLevel;
   pEmpLevel = new EmployeeLevel;
   * pEmpLevel = * rhs.pEmpLevel;
   myAge = rhs.myAge;
   return *this;
 } 

Note that we first delete pEmpLevel, freeing this memory, and then we reallocate memory and reassign. There is still a problem, however. It is possible to write:

   Employee fred, wilma;
   fred = wilma;
   wilma = fred;

The problem here is that this second statement is much the same as writing

   fred = fred;

Now the object and rhs are the same. The first thing you do is delete pEmpLevel. You then reassign memory and attempt to copy *rhs.pEmpLevel into that newly created memory, but pEmpLevel has already been deleted. Whoops. To protect yourself, add these two lines to the beginning of the method:

   if (this == &rhs)
      return *this;

Thus, if the two objects are the same, there is no work to be done. Here's the complete assignment operator:

Employee & Employee::operator=(const Employee & rhs)
{
   if (this == &rhs)
      return *this;
   delete pEmpLevel;
   pEmpLevel = new EmployeeLevel;
   * pEmpLevel = * rhs.pEmpLevel;
   myAge = rhs.myAge;
   return *this;
} 

© 1998 by Wrox Press. All rights reserved.