Automatic Generation of Clone Method

W

woessner

I have a lot of classes which derive from a common base class. I want
to be able to clone objects of these types so I have given the base
class a pure virtual clone method. The derived classes all have
complete copy constructors so the cloning process will consiste of
"return new Derived(*this);". Here's the setup:

struct Base
{
virtual Base* Clone() const = 0;
};
struct Derived: public Base
{
Derived* Clone() const { return new Derived(*this); }
};

My question is: Is there any way to automatically generate the clone
methods. I admit, I'm being really lazy, here. The Clone method is
only 1 line long, but I have dozens of classes that need it. So it
would be nice if there was some way of automatically doing it. Maybe
some magic combination of templates and inheritance?

Thanks in advance,
Bill
 
K

Kai-Uwe Bux

I have a lot of classes which derive from a common base class. I want
to be able to clone objects of these types so I have given the base
class a pure virtual clone method. The derived classes all have
complete copy constructors so the cloning process will consiste of
"return new Derived(*this);". Here's the setup:

struct Base
{
virtual Base* Clone() const = 0;
};
struct Derived: public Base
{
Derived* Clone() const { return new Derived(*this); }
};

My question is: Is there any way to automatically generate the clone
methods. I admit, I'm being really lazy, here. The Clone method is
only 1 line long, but I have dozens of classes that need it. So it
would be nice if there was some way of automatically doing it. Maybe
some magic combination of templates and inheritance?

Not exactly automatic generation of clone methods, however, if you google
the archives for clone_ptr or copy_ptr, you will find a smart pointer
template that, by and large, makes clone methods superfluous.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,152
Latest member
LorettaGur
Top