Jump to content

Assignment operator (C++)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Nemochovsky (talk | contribs) at 13:49, 5 November 2006. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Overloading operator = makes your source code more transparent. Overloaded operator = is called when one object is assigned to some other existing object. This differs from an initialization using some existing object, in that case a copy constructor is used.

object_1.copy(object_2);	// example without overloaded operator =

object_1 = object_2;

It is not needed to overload operator =, if your objects don’t contain pointers. In this case, default operator = copies your objects correctly. But if your objects contain pointers and you need to make a deep copy, overloading the operator = with a method is a nice solution. You should:

  1. Not do anything, if assigning to the object itself, eg:
    array_1 = array_1;
  2. Dealocate memory
  3. Allocate new memory
  4. Copy entries
class My_Array {
	int count;
	int *array;
public:
	...
	My_Array& operator=(const My_Array&);
}
My_Array& My_Array::operator=(const My_Array& in) {
      if (this != &in) {                      // 1)
		delete [] array;              // 2)
		array = new int[in.count];    // 3)
		count = in.count;             // \
		for (int i=0; i<count; i++)   //  > 4)
		   array[i] = in.array[i];    // /
      }
      return *this;
}

Deallocating and subsequent allocating of a new memory is not necessary, if the allocated memory is big enough for the new data and we don’t mind wasting memory in case the new data needs less space.

The reason why operator = returns My_Array& instead of void is simple. It allows us to concatenate assignments like this:

array_1 = array_2 = array_3; // array_3 is assigned to array_2 
                             // and then array_2 is assigned to array_1