[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: copy constructor Up: A class definition example Previous: assignment operator

this

But problems remain. If the programmer writes a=a, the delete command above frees a.fingerprint, which we don't want to free. We can get round this by making use of the this variable, which is automatically set to be the address of the current object. If the code above is bracketted by if (this != &b) { ... } then it's safe.

There's another improvement that we can make. So that assignments like a=b=c can work, it's better not to return void.

criminal const& criminal::operator=(criminal const &b)
{
 if (this != &b) {
   name=b.name;
   fingerprint_size=b.fingerprint_size;
   delete fingerprint;
   fingerprint = new char[fingerprint_size];
   for (int i=0;i<fingerprint_size;i++)
      fingerprint[i]=b.fingerprint[i];
 }
 return *this;
}



Tim Love
2001-07-05