471,863 Members | 1,217 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,863 software developers and data experts.

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 2365
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
NeoPa
reply views Thread by NeoPa | last post: by
reply views Thread by YellowAndGreen | last post: by
aboka
reply views Thread by aboka | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.