previous | start | next

Rule of 3, part 3: Assignment Operator

When one Employee variable is assigned to another, the compiler makes a copy, but it does not use the copy constructor!

The copy constructor is not sufficient because, the old value of the Employee must be deleted in an assignment to avoid a memory leak.

The assignment operator= differs from the copy constructor only because of this deletion.

void Employee::operator=(const Employee& other)
{
  if (  other == &this ) { // What?
    return;
  }
  delete [] name;
  // rest is the same as the copy constructor
  name = new char[strlen(other.name) + 1];
  strcpy(name, other.name);
  salary = other.salary;
}



previous | start | next