473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Duplicating objects with a common base class

I have a system in which potentialy 100's of classes derive directly
from a common base class. I will often have a pointer of the base class
type which points to an object of a derived class. Now the hard bit: I
need to be able to create a copy of the object.

I know I could write a virtual Duplicate() function in the base class,
and then override it in each of the derived classes, but that seems very
time consuming when the code is going to look more or less identical in
each case.
Any Ideas?

TIA

Pete Nudd
Jul 22 '05 #1
3 1373

"Pete Nudd" <pe********@nospampleasebaesystems.com> wrote in message
news:40**************@nospampleasebaesystems.com.. .
I have a system in which potentialy 100's of classes derive directly
from a common base class. I will often have a pointer of the base class
type which points to an object of a derived class. Now the hard bit: I
need to be able to create a copy of the object.

I know I could write a virtual Duplicate() function in the base class,
and then override it in each of the derived classes, but that seems very
time consuming when the code is going to look more or less identical in
each case.
Any Ideas?

TIA

Pete Nudd


You're doing it the right way, there isn't a better way in C++. Some people
would cut out some of the repetition by using a macro but personally I
wouldn't recommend it. Its only a one line function so it not too hard to
write it each time.

john

BTW the traditional name for the function you are calling Duplicate is
Clone.
Jul 22 '05 #2
Pete Nudd wrote:
I have a system in which potentialy 100's of classes
derive directly from a common base class. I will often
have a pointer of the base class type which points to an
object of a derived class. Now the hard bit: I need to be
able to create a copy of the object.

I know I could write a virtual Duplicate() function in
the base class, and then override it in each of the
derived classes, but that seems very time consuming when
the code is going to look more or less identical in each
case.

Any Ideas?


You could use a template to supply a clone() function.
(I think -- you might want a second opinion because I'm
making this up as I go along.) Say your base is:

class Base
{
public:
virtual Base* clone() const = 0;
virtual ~Base() {}
};

Create a template that defines clone() for any type T
and is itself derived from Base:

template<class T>
class CloneableBase : public Base
{
public:
Base* clone() const
{
return new T(dynamic_cast<const T&>(*this));
}
};

Now inherit from Cloneable instead of using Base
directly:

class Foo : public CloneableBase<Foo> {};
class Bar : public CloneableBase<Bar> {};

And you can write:

Base* pb1 = new Foo;
Base* pb2 = pb1->clone();
Jul 22 '05 #3
Derek wrote:

Pete Nudd wrote: [snip]
You could use a template to supply a clone() function.
(I think -- you might want a second opinion because I'm
making this up as I go along.) Say your base is:

class Base
{
public:
virtual Base* clone() const = 0;
virtual ~Base() {}
};

Create a template that defines clone() for any type T
and is itself derived from Base:

template<class T>
class CloneableBase : public Base
{
public:
Base* clone() const
{
return new T(dynamic_cast<const T&>(*this));
}
};

Now inherit from Cloneable instead of using Base
directly:

class Foo : public CloneableBase<Foo> {};
class Bar : public CloneableBase<Bar> {};

And you can write:

Base* pb1 = new Foo;
Base* pb2 = pb1->clone();


Nitpicking: I'd disagree with the use of dynamic_cast here (other than
for debugging). If CloneableBase<T> is used as intended:
class Bar : public CloneableBase<Bar> {};

then the result of dynamic_cast is equivalent to static_cast.
The only time its observed behaviour will differ from that of static_cast
is when someone grossly misuses CloneableBase<T>, e.g.
class Bar : public CloneableBase<Foo> {};

This, however, should be detected at compile time and, at any rate, never
happen in the production code, so static_cast will do. If this still
didn't sound safe enough, I'd just revert to the original scheme.

(FWIW, I use dynamic_cast only when I really have to (i.e. when downcasting
can only be resolved at run-time and must be controlled for safety, and
there are no design alternatives). The former use is a domain serviced
well enough by virtual functions alone. On a practical note, at least
some popular implementations of dynamic_cast are very inefficient).

Denis
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Paul | last post by:
In real life situation, do we ever come across a situation where we would need two base objects in an object. A snippet is worth 1000 words (: so... class Base { }; class Derived1:public Base...
5
by: ben | last post by:
Hi guyz, Is it possible to create objects of a class whose definition as well as declaration is not available in advance? Consider the following program: #include<iostream> #include<fstream>
13
by: Markus Ernst | last post by:
Hello In a content administration tool I call classes from inside classes in order to separate the admin functions from the display-only functions: class book { var $title; var $author;...
5
by: wrecker | last post by:
Hi all, I have a few common methods that I need to use at different points in my web application. I'm wondering where the best place would be to put these? I think that I have three options. ...
161
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.....
4
by: esuvs81 | last post by:
Hi, imagine I have a simple hierarchy with three classes - 'Base', 'Derived1', and Derived2. Base is an absrtact class and the two Derived classes are concrete. Imagine at some point in my code I...
6
by: Osiris | last post by:
Is the following intuitively feasible in Python: I have an array (I come from C) of identical objects, called sections. These sections have some feature, say a length, measured in mm, which is...
3
by: orkonoid | last post by:
Hello, I am having trouble with a Polymorphism issue using container classes. I have a longwinded and shortwinded version of my question: Shortwinded version: How can I store base class...
15
by: Juha Nieminen | last post by:
I'm sure this is not a new idea, but I have never heard about it before. I'm wondering if this could work: Assume that you have a common base class and a bunch of classes derived from it, and...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.