469,621 Members | 1,806 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,621 developers. It's quick & easy.

Automatic Generation of Clone Method

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

Oct 9 '06 #1
1 2281
wo******@gmail.com wrote:
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
Oct 9 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Jason Evans | last post: by
reply views Thread by Rasmus Fogh | last post: by
15 posts views Thread by Kannan Goundan | last post: by
1 post views Thread by Alex D. | last post: by
4 posts views Thread by Petterson Mikael | last post: by
2 posts views Thread by Steven | last post: by
14 posts views Thread by Hamed | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.