Friday, January 29, 2010

Overloaded Assignment

When to define assignment (and a copy constructor and destructor)
If your object has a pointer to dynamically allocated memory, eg allocated in the constructor, you will want to make a deep copy of the object. Deep copies require overloading assignment, as well as defining a copy constructor and a destructor).

Example
//--- file Person.h
. . .
class Person {
private:
char* _name;
int _id;
public:
Person& Person::operator=(const Person& p);
. . .
}
//--- file Person.cpp
. . .
//=================================================== operator=
Person& Person::operator=(const Person& p) {
if (this != &p) { // make sure not same object
delete [] _name; // Delete old name's memory.
_name = new char[strlen(p._name)+1]; // Get new space
strcpy(_name, p._name); // Copy new name
_id = p._id; // Copy id
}
return *this; // Return ref for multiple assignment
}//end operator=

No comments:

Post a Comment