Normally if you want to copy something, you just copy it.
|
std::string s = getstr(); // invokes the copy constructor
|
However, if you have an interface, you really don't have the thing. And when you do somthing to it, you don't do it directly, but through the interface using virtual functions. However, when it comes to copying one, you need a virtual constructor. As C++ doesn't support this, the Clone Pattern is used for similar effect. For example:
1 2 3 4
|
Shape* s CopyShape(Shape* s)
{
return s->Clone();
}
|
So it only makes sense to invoke the Clone Pattern if your object is part of an object hierachy. Otherwise don't use it.
Now, how we can fix your code. If your class is a standalone thing (an abstract data type), you just use the built in mechanisms, that is, a define a copy constuctor and assignment operator. And as your class doesn't hold pointers to things, the default implementation should suffice.
1 2 3 4 5 6 7
|
class Foo
{
int m_id;
public:
void setID(int id) { m_id = id; }
};
|
You don't need clone on this.
Now, if Foo was part of a hierarchy, we're back to using Clone.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Base
{
public:
virtual ~Base() = 0;
virtual Base* Clone() = 0;
};
Base::~Base()
{
}
class Foo : public Base
{
int m_id;
public:
void setID(int id) { m_id = id; }
Foo() : m_id(0) {}
~Foo() {}
Base* Clone() { return new Foo(*this); } // use copy constructor for concrete instance
};
|