473,654 Members | 3,040 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cloning C++ objects

Hi,

I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:

class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }
// ...
}

compiler tells me, that I cannot allocate object of class String,
because some methods are "pure". There are some more virtual methods in
Object, but there are all implemented in String. What should I do to
solve this problem?

Paul PAZABO Zaborski

Dec 4 '06 #1
10 7602
paz...@gmail.co m wrote:
Hi,

I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:

class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }
// ...
}

compiler tells me, that I cannot allocate object of class String,
because some methods are "pure". There are some more virtual methods in
Object, but there are all implemented in String. What should I do to
solve this problem?
It's likely that you forgot to implement something from Object (or that
you added a pure virtual function in String). Post more code, and we
can probably tell you what the problem is.

Cheers! --M

Dec 4 '06 #2

mlimber wrote:
paz...@gmail.co m wrote:
Hi,

I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:

class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }
// ...
}

compiler tells me, that I cannot allocate object of class String,
because some methods are "pure". There are some more virtual methods in
Object, but there are all implemented in String. What should I do to
solve this problem?

It's likely that you forgot to implement something from Object (or that
you added a pure virtual function in String). Post more code, and we
can probably tell you what the problem is.

Cheers! --M
Oh.. I see the problem.. I put "const" after some methods in Object,
but I forgot to do it in String, so compiler considered it as abstract
class.
Anyway, thanks for help :)

Dec 4 '06 #3
pa****@gmail.co m schrieb:
Hi,

I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:

class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }
I would return a String* here:

String* clone() const { return new String(*this); }

So you can clone a String and get a String without casting.
// ...
}
--
Thomas
http://www.netmeister.org/news/learn2quote.html
Dec 5 '06 #4

Thomas J. Gritzan wrote:
pa****@gmail.co m schrieb:
Hi,

I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:

class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }

I would return a String* here:

String* clone() const { return new String(*this); }

So you can clone a String and get a String without casting.

Generally, the reason to want to implement a virtual clone() type
method is when you are dealing with polymorphic objects and aren't (or
don't want to be) aware of their exact types. You are generally
dealing with pointers to base classes that define clone() in terms of
themselves. If you already knew the type of the object why wouldn't
you just invoke new with a copy constructor?

Regards,

Jon Trauntvein

Dec 5 '06 #5
JH Trauntvein wrote:
>>>
class Object {
public:
virtual Object * clone() const = 0;
// ...
}

class String : public Object {
public:
Object * clone() const { return new String(*this); }
I would return a String* here:

String* clone() const { return new String(*this); }

So you can clone a String and get a String without casting.


Generally, the reason to want to implement a virtual clone() type
method is when you are dealing with polymorphic objects and aren't (or
don't want to be) aware of their exact types. You are generally
dealing with pointers to base classes that define clone() in terms of
themselves. If you already knew the type of the object why wouldn't
you just invoke new with a copy constructor?
I was going to say the same thing, but in general, it's a little more
complicated. Suppose there's a class derived from String, and you've got
a String*. Then having String::clone() return a String* is handy,
because you can clone the object that the String* points to without
having to cast the returned pointer back from Object*.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Dec 5 '06 #6
On Dec 5, 1:20 pm, "JH Trauntvein" <j.trauntv...@c omcast.netwrote :
Thomas J. Gritzan wrote:
paz...@gmail.co m schrieb:
Hi,
I'm trying to somehow implement polymorphic object cloning (just as it
is in Java), but when I write:
class Object {
public:
virtual Object * clone() const = 0;
// ...
}
class String : public Object {
public:
Object * clone() const { return new String(*this); }
I would return a String* here:
String* clone() const { return new String(*this); }
So you can clone a String and get a String without casting.General ly, the reason to want to implement a virtual clone() type
method is when you are dealing with polymorphic objects and aren't (or
don't want to be) aware of their exact types. You are generally
dealing with pointers to base classes that define clone() in terms of
themselves. If you already knew the type of the object why wouldn't
you just invoke new with a copy constructor?
Which means that you have something like this:
struct Object {
virtual Object* clone() {
std::cout << "obj\n";
return new Object(*this);
}
};

struct String : public Object {
int a;
virtual String* clone() {
std::cout << "str\n";
return new String(*this);
}
};

int main() {
String* str = new String;
Object* obj1 = str;
Object* obj2 = obj1->clone();
}

As you see if you run the code it's the String::clone() function that
is called, even tough you didn't know that it was a String. If you
didn't use the String::clone() you would not have been able to create a
clone since there is no 'a'-variable in Object, so when calling the
copy-constructor of Object you get an Object and not a String. In other
words, returning a String* does not prevent you from cloning a String
from an Object-pointer, but allows you to clone a String also from a
String-pointer.

--
Erik Wikström

Dec 5 '06 #7

er****@student. chalmers.se wrote:
>
Which means that you have something like this:
struct Object {
virtual Object* clone() {
std::cout << "obj\n";
return new Object(*this);
}
};

struct String : public Object {
int a;
virtual String* clone() {
std::cout << "str\n";
return new String(*this);
}
};

int main() {
String* str = new String;
Object* obj1 = str;
Object* obj2 = obj1->clone();
}

As you see if you run the code it's the String::clone() function that
is called, even tough you didn't know that it was a String. If you
didn't use the String::clone() you would not have been able to create a
clone since there is no 'a'-variable in Object, so when calling the
copy-constructor of Object you get an Object and not a String. In other
words, returning a String* does not prevent you from cloning a String
from an Object-pointer, but allows you to clone a String also from a
String-pointer.
I don't have a reference in front of me but I believe that the return
type is a part of the function signature. If that is the case, the
overloaded version of clone will not act as a virtual method but rather
overshadow the virtual method.

Regards,

Jon Trauntvein

Dec 5 '06 #8
JH Trauntvein wrote:
>
I don't have a reference in front of me but I believe that the return
type is a part of the function signature. If that is the case, the
overloaded version of clone will not act as a virtual method but rather
overshadow the virtual method.
When the function in the base class returns a pointer or reference to a
class type and the function in the derived class returns a pointer or
reference, respectively, to a type derived from that type, the derived
version still overrides the base version.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Dec 5 '06 #9
JH Trauntvein schrieb:
I don't have a reference in front of me but I believe that the return
type is a part of the function signature. If that is the case, the
overloaded version of clone will not act as a virtual method but rather
overshadow the virtual method.
You can override a virtual member function and change its return type, but
the new return type must be a derived class. It's called "Covariant Return
Type".

In Java, you can't (don't know if they introduced it in a newer version),
so you have to downcast cloned Objects:

String s = new String("some text");
String cloned = s.clone(); // error, clone() returns Object!

But you already _now_ here, that clone() returns a String, so casting would
be superflous. With Covariant Return Types, you can let the compiler know
that it's a String.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Dec 5 '06 #10

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

Similar topics

4
2457
by: Tom | last post by:
Hey ho, The release of PHP5 seemed like a good reason to try to learn it once more... I'm reading through the O'Reilly PHP/MySQL book and right now, I'm fiddling with objects. I just discovered the proper way to clone objects is *not* "$b = $a->__clone();", as it reads in the book, but "$b = clone $a". Right?
1
9163
by: Cody Manix | last post by:
iam trying to program a copy constructor that is able to create a bitwise copy of its argument: MyClass { int a; // lots of different fields goes here float x; MyClass (MyClass my) {
11
3002
by: K.K. | last post by:
Suppose I have a class called Vehicle with many fields. Now I make a new class derived from Vehicle called Car. I'd like to make a method to copy the data from a Vehicle instance to a Car instance. Is writing a long series of assignments in a Clone() statement my only option? I know that I can write a Clone method using MemberwiseClone(), but my understanding is that the object created by MemberwiseClone is of the same type.
8
4865
by: Tom | last post by:
I've a problem. I want to clone an object having a list of other objects (and so on :/). Do you know any other way than ICloneable.Clone() implementation for all classes in the way? Help..
6
8388
by: J Williams | last post by:
I'm using axWebBrowser control and HTML DOM in a VB .NET Windows application to create a new HTML document by cloning nodes. The function below is called from the axWebBrowser1_DocumentComplete event using: Dim mNewDoc As mshtml.IHTMLDocument3 mNewDoc = NewDoc(axWebBrowser1.Document) Private Function NewDoc(ByVal mInputDoc As mshtml.IHTMLDocument3) As mshtml.IHTMLDocument3
1
2051
by: illegal.prime | last post by:
I would like to have an array of objects (whose class I define) and then just invoke either: MyClass clonedArray = (MyClass) myArray.Clone(); OR Array.Copy(myArray, clonedArray, myArray.Length); and have an array of cloned objects (i.e. the new array of objects aren't the objects contained in my original array). But instead it seems necessary for me to have to iterate over my entire array and individually clone each element in the...
1
1724
by: colmkav | last post by:
Hi, what is the main reason why cloning is done to tables in Access VBA code? regards Colm
3
8746
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. ...
9
13292
gits
by: gits | last post by:
This short article introduces a method that may be used to create a 'deep-copy' of an javascript object. You might ask: 'Wherefore do we need this?' ... Answer: 'Only variable-values of the basic data-types string, int, float, boolean and to make the confusion perfect :) functions too! are passed by value, all others are passed by reference.' This means, when you create an object a, like in the code below, and you assign object a to variable b...
0
8375
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8290
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
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8707
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...
0
8593
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...
0
5622
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
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.