4.9 Assignment Operator




A class can define its own assignment operator. The assignment operator defines what actions occur when a value is assigned to an object. A class-specific assignment operator is needed because, similar to a copy constructor, special actions may need to be taken to insure that the object behaves in a reasonable way when objects of the same class are assigned to each other. By default, object assignment is bitwise: a bit-by-bit copy is done from the the source object (the one on the right hand side of the assignment operator) to the target object (the one on the left hand side of the assignment operator).

The Message class is used to illustrate the need for a class-specific assignment operator. The following example shows two Message objects, one of which is assigned to the other:


	Message targetMsg("Hello Word");
	Message sourceMsg("MacroSoft Inc.");

	...

	targetMsg = sourceMsg;		// assignment
Before the assignment statement is executed the structure of the objects is as follows:

Before Assignment Statement

After the default (bitwise) assignment operation is completed the situation is this:

After Assignment Statement

There are two obvious (and serious) problems created by the default assignment. First, a memory leak has been created because the original targetMsg string is no long accessible but has not been returned to the memory management system. Second, both objects (targetMsg and sourceMsg) point to the same character string. Because they point to the same string, the destruction of one of the Message objects causes the other Message object to point to memory with undefined contents.

What is desired by the assignment operator is the following situation:

Desired Result of Assignment

In this situation, the original targetMsg string (Hello World") has been deallocated and the targetMsg now points to a copy of the original sourceMsg string ("MacroSoft In.c").

The Message class shown below includes a class-specific assignment operator:

   class Message {
     private:
	char* message;
        ...
     public:
	...
	void operator=(const Message& source);
	...
   };


   void Message::operator=(const Message& source) {
	delete message;	         	       // deallocate previous string
	message = copystring(source.message); // copy new string
   }

The "name" of the assignment operator is "operator=". The "operator" part is mandatory and signifies that a class-specific definition is being given for a standard C++ operator. Which standard C++ operator is being given a class-specific meaning is determined by the symbol(s) that follow immediately after "operator".


Next Stop


Exercises

  1. Add an assignment operator to the Shape class.Test your code with a simple main program.

  2. Add an assignment operator to the Location class.Test your code with a simple main program.

Last Updated: February 26, 1996 / kafura@cs.vt.edu