0

If I had a overloaded assignment operator that need to deep-copy a class, how would I go about doing it? class Person contains a Name class

Person& Person::operator=(Person& per){
if (this==&per){return *this;}
// my attempt at making a deep-copy but it crashes  
this->name = *new Name(per.name);
}

in the name class copy-constructor and assignment operator

Name::Name(Name& name){

if(name.firstName){
firstName = new char [strlen(name.firstName)+1];
strcpy(firstName,name.firstName);
}

Name& Name::operator=(Name& newName){
if(this==&newName){return *this;}

if(newName.firstName){
firstName = new char [strlen(newName.firstName)+1];
strcpy(firstName,newName.firstName);

return *this;
}
odinthenerd
  • 5,422
  • 1
  • 32
  • 61
Tiber
  • 116
  • 1
  • 18
  • First of all assignment and copy constructor take `const X&`and not just `X&`. Second, what is the type of `name` ? `Name&` ? If yes, it won't work. If no, do not use `new` cause you have a leak. – Johan Dec 07 '13 at 21:27
  • Uee copy and swap Idiom : http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom – Davidbrcz Dec 07 '13 at 21:32

1 Answers1

1

I would leverage the existing copy constructor, destructor, and added swap() function:

Name& Name::operator= (Name other) {
    this->swap(other);
    return *this;
}

All copy assignments I'm implementing look like this implementation. The missing swap() function is also trivial to write:

void Name::swap(Name& other) {
    std::swap(this->firstName, other.firstName);
}

Likewise for Person.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380