Overloading the assignment operator

Now that we have the ability to create variable size arrays using dynamic memory allocation, it becomes imperative to overload the assignment operator, rather than using the default assignment operator.

Since the default assignment operator copies member variables from one object to another, the address of the dynamic memory that has been allocated will also be copied over. This means that it is possible to have two separate objects that are referencing the same piece of dynamic memory.

X x1, x2;
... manipulate x1 ..

x1 = x2

When the assignment operator is overloaded, it MUST be a member function.

Prototype:  return_type operator=(const class_name &);

Header:     return_type class_name::operator=(const class_name &obj_name)

Unlike the copy constructor, there is no guarantee that the argument on the left and right side of the equal sign will be different. Therefore it is important to check for self assignment within the function for overloading the assignment operator.

The check can be done by comparing the contents of the this pointer with the address of the passed in argument. If they are the same, do nothing. If they are different, proceed with the copying.

With the built in classes it is possible to "string" together assignment statements. It might be nice to be able to add this feature to user defined classes. To accomplish this, the return type from the assignment operator function is typically a reference to a class object.