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; // assignmentBefore 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".
|
Exercises |
Last Updated: February 26, 1996 / kafura@cs.vt.edu