Implementation of a clone method with private copy constructor and assignment operator.
void makeCopy(Parent *instanceToCopy)
{
Child childInstance;
/* won't work anymore:
because of private copy constructor and assignment operator */
Child copy1 = childInstance;
Child copy2(childInstance);
/* won't work anymore:
the instance would lose all 'Child' specific data! */
Parent dangerousCopy(instanceToCopy);
/* will work for now:
copying correctly with the clone method */
Clone *secureCopy = instanceToCopy.clone();
// ...
}
class Clone
{
public:
virtual ~Clone
(void) {}
// pure virtual clone method
virtual Clone *clone
(void) const = 0;
};
class Parent : public Clone
{
private:
// private copy constructor
Parent
(const Parent &);
// private copy assignment operator
Parent &operator =
(const Parent &);
public:
Parent
(void) {}
// clone method to create a copy
Clone *clone
(void) const {return new Parent(*this);}
};
class Child : public Parent
{
private:
// private copy constructor
Child
(const Child &);
// private copy assignment operator
Child &operator =
(const Child &);
public:
Child
(void) {}
// clone method to create a copy
Clone *clone
(void) const {return new Child(*this);}
};
Parent::Parent(const Parent &source)
{
/*
copy data from source instance to this one:
property1 = source.property1;
...
*/
}
Parent &Parent::operator = (const Parent &source)
{
/*
copy data from source instance to this one:
property1 = source.property1;
...
*/
return *this;
}
Child::Child(const Child &source)
{
/*
copy data from source instance to this one:
property1 = source.property1;
...
*/
}
Child &Child::operator = (const Child &source)
{
/*
copy data from source instance to this one:
property1 = source.property1;
...
*/
return *this;
}