[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Redefining [ ] Up: A class definition example Previous: this

copy constructor

But there's still a problem! Suppose the programmer writes criminal a=b;. a is being created, so a constructor is called - not an assignment. Thus we need to write another constructor routine using similar ideas to those used in assignment. Note that in this case resources don't need deleting, and that this needn't be checked (because criminal a=a; is illegal).

Putting all these ideas together, and sharing code where possible we get

void criminal::copy (criminal const &b)
{
 name=b.name;
 fingerprint_size=b.fingerprint_size;
 fingerprint = new char[fingerprint_size];
 for (int i=0;i<fingerprint_size;i++)
    fingerprint[i]=b.fingerprint[i];

}

void criminal::destroy()
{
 delete fingerprint;

}

// Assignment Operator
criminal const& criminal::operator=(criminal const &b)
{
 if (this != &b) {
  destroy();
  copy(b);
 }
 return *this;
}

// Default Constructor
criminal::criminal()
{
  fingerprint=0;
  fingerprint_size=0;
}


// Copy Constructor
criminal::criminal(criminal const &b)
{
  copy(b);
}

// Destructor
void criminal::~criminal()
{
  destroy();
}

This seems like a lot of work, but it's necessary if objects use pointers to resources. You might think that by avoiding the use of commands like a=a in your own code, you can save yourself the trouble of writing these extra routines, but sometimes the problem situations aren't obvious. For instance, the copy constructor is called when an object is returned or used as an argument to a routine. Better safe than sorry.



Tim Love
2001-07-05