previous | start | next

## Automatic Memory Management

- The remedy is to overload the `operator=` to make the assignment safe by deleting the only `Employee` object, and making a copy of the new `Employee` object.

  >     Department& Department::operator=(const Department& b)
  >     {
  >        if (this != & b)
  >        {
  >           name = b.name;
  >           delete receptionist;
  >           if (b.receptionist == NULL)
  >              receptionist == NULL;
  >           else
  >              receptionist = new Employee(b.receptionist->get_name(),
  >                 b.receptionist->get_salary());
  >         }
  >         return *this;
  >     }

- Unlike most other operators, the `operator=` must be a member function.
- Special care must be taken to avoid a destructive "self-assignment."
- A return by reference is required to handle chaining of assignments, such as.

  >     z = y = x;

- You should always overload the = operator if your class has data fields that are pointers, and a simple copy of objects leads to dangerous shared pointers.

previous | start | next