![]() |
|||||||||
4.10 Assignment Operator |
|||||||||
|
The Message class illustrates 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:
After the default (bitwise) assignment operation is completed the situation is this:
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 longer 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:
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, Inc."). 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 the "operator" keyword.
Tasks
|
|||||||||
|
|||||||||