Wednesday, September 12, 2007

About Copy Constructor

In the example below, push_back will call the copy constructor of Family implicitly. In this case, it's a deep copy. If we comment out the copy constructor, a default one will gets called, which is a shallow copy.

If we have at least one complex object in a class, we should think about writing our own copy constructor. (choose between deep copy and shallow copy) If there's no complex object in the class, a default copy constructor will do since there's no difference between deep and shallow copy in this case. Remember that if we provide our own copy constructor, we also need to write the destructor so the complex objects can be deallocated.

class Person
{
public:
int age;
Person()
{
age = 0;
}
};

class Family
{
public:
Person* houseHold;
int aptNum;
Family()
{
houseHold = 0;
aptNum = 0;
}
Family(const Family& family)
{
this->houseHold = new Person(*family.houseHold);
this->aptNum = family.aptNum;
}
};

main()
{
vector vecF;
Person* p = new Person();
p->age = 30;
Family* f = new Family();
f->houseHold = p;
f->aptNum = 100;
vecF.push_back(*f);
delete f;
delete p;
cout <<
vecF.at(0).houseHold->age << endl << vecF.at(0).aptNum << endl;
getchar();
}

No comments: