473,854 Members | 1,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

deep copy of a polymorphic object with only a base ptr?

Hello!

Suppose I have a class base, with virtual methods and a virtual
destructor and a bunch of classes,
derived1, derived2, ... which publicly derive from base. I then have a
pointer

base* foo;

which a complicated code allocates as one of derived's and sets up.
Later on I have polymorphic
access to the underlying object via this base pointer foo.

At one point I need to create a deep copy of the object behind foo,
i.e. I have

base* foo_copy; // how do I deep-copy (*foo) into here?

This needs to copy a derived class, but, since I only have a base
pointer I do not know how
to go on about it, the first obstacle being the typename needed in the
new-expression which
would be used to allocate memory for foo_copy.

I tried new typeof(*foo), but, as far as I see, it is not
polymorphic and new'ed me a base class.

Sure, I could try dynamic_cast<>' ing foo to every possible derived
and see which one does
not return NULL (or is it bad_cast?) but that would involve a nasty
switch, wouldn't it?

So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?

Also, both the base classes and the derived classes do not have
(user-defined) copy ctors,
since they are almost-POD and I'm satisfied with the memberwise copy
construction. Is this
compiler-generated copy ctor safe to use here?

TIA,
- J.

Aug 20 '07 #1
3 3916
Hi!

ja************@ gmail.com schrieb:
So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?
The standard solution is to extend the base class interface:

class Base
{
protected:
virtual Base* doClone() const =0;
public:
Base* clone() const { return doClone(); }
};

class Dev1 : public Base
{
protected:
virtual Dev1* doClone() const
{ return new Dev1(*this); }
public:
Dev1* clone() const { return doClone(); }
};

Then you can "clone" objects:
Base* const b1 = new Dev1;
Base* const b2 = b1->clone();
Also, both the base classes and the derived classes do not have
(user-defined) copy ctors,
since they are almost-POD and I'm satisfied with the memberwise copy
construction. Is this
compiler-generated copy ctor safe to use here?
The generated copy ctor is defined as memberwise copy. It should not
only be fine in your case, but it is usually a good choice.

HTH,
Frank
Aug 20 '07 #2
On Aug 20, 4:20 pm, jacek.dzied...@ gmail.com wrote:
Hello!

Suppose I have a class base, with virtual methods and a virtual
destructor and a bunch of classes,
derived1, derived2, ... which publicly derive from base. I then have a
pointer

base* foo;

which a complicated code allocates as one of derived's and sets up.
Later on I have polymorphic
access to the underlying object via this base pointer foo.

At one point I need to create a deep copy of the object behind foo,
i.e. I have

base* foo_copy; // how do I deep-copy (*foo) into here?

This needs to copy a derived class, but, since I only have a base
pointer I do not know how
to go on about it, the first obstacle being the typename needed in the
new-expression which
would be used to allocate memory for foo_copy.
You can define virtual clone() member function. Refer
http://www.parashift.com/c++-faq-lit....html#faq-20.8
for details.
I tried new typeof(*foo), but, as far as I see, it is not
polymorphic and new'ed me a base class.

Sure, I could try dynamic_cast<>' ing foo to every possible derived
and see which one does
not return NULL (or is it bad_cast?) but that would involve a nasty
switch, wouldn't it?

So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?

Also, both the base classes and the derived classes do not have
(user-defined) copy ctors,
since they are almost-POD and I'm satisfied with the memberwise copy
construction. Is this
compiler-generated copy ctor safe to use here?
If you are "satisfied" with memberwise copy, then it is probably the
correct choice.

-N
Aug 20 '07 #3
On Aug 20, 1:41 pm, Frank Birbacher <bloodymir.c... @gmx.netwrote:
Hi!

jacek.dzied...@ gmail.com schrieb:
So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?

The standard solution is to extend the base class interface:
[...]

Thank you very much, (and to Neelash Bodas also) for the solution!

cheers,
- J.

Aug 20 '07 #4

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

Similar topics

42
5820
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
5
3292
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the assignment Student* john = michael; both john and michael share the same object. This type of an assignment is different then value-assignmnet semantics used by class variables, as in
20
2238
by: verec | last post by:
One problem I've come accross in designing a specific version of auto_ptr is that I have to disntiguish between "polymorphic" arguments and "plain" ones, because the template has to, internally, cast to void *. Specifically, template <typename T> void f(T * t) { void * p = dynamic_cast<void *>(t) ; } will not compile if T isn't of a class that has somewhere at least
4
52316
by: fperfect13 | last post by:
Hi, I wanted to perform a deep copy of an array. Searching on google I ran into different opinions : C# Interview Questions (http://blogs.wwwcoder.com/tsvmadhav/archive/2005/04/08/2882.aspx) 10.What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
12
1456
by: Bob | last post by:
Hi, 'Shadowed' properties are not polymorphic. (See thread 'Inheritance and late binding') They should be. Problem: Base class has read only property 'X'. Derived class must have read / write property 'X'. Can't override Base class 'X' because of different structure. So you Shadow the base class 'X' in the derived class. Pass an instance of the derived class to a function.
4
3043
by: jjkboswell | last post by:
I have an XSD which I have generated a class from using the xsd.exe tool. My XSD contains complex types within it, so that the generated class has member variables which are of types that are also defined in the XSD. I deserialize XML data into instances of that class, and serialize back to XML. So far so good. However, in my code I have the concept of wanting to create new copies of these deserialized objects and modifying some of...
11
3443
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered like mine. ...
3
8756
by: raylopez99 | last post by:
The "C# Cookbook" (O'Reilly / Jay Hilyard), section 3.26, is on deep cloning versus shallow cloning. The scanned pages of this book are found here: http://www.sendspace.com/file/mjyocg (Word format, 3 pp) My question, coming from a C++ background where deep copying is done, is why in C# you would do either deep or shallow copying as suggested by O'Reilly (using the "ICloneable" inhereited interface), at least for the .NET framework. ...
0
9751
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10679
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10756
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7914
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5941
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4560
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3186
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.