473,586 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cloning objects

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)
{
// create an exact copy of mc here
}
}

normaly, object.MemberWi seClone() would be the way to go but it seems its
useless within a constructor.
is there another way (without copying every item manually)?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu
[noncommercial and no fucking ads]

Nov 15 '05 #1
1 9158
Hi Cody --

Doing so might cause some tricky behavior for a class. If you think about
classes being able to be inherited, it's possible that the instance passed
into the "copy constructor" is actually a subclass of that type, with
different fields, so one can't just always make a direct copy. For
classes, I'm pretty sure that the only option is to write a programmatic
copy.

It's certainly possible to make a quick copy if your data structure is a C#
struct. Structs have certain constraints, such as they can't be extended
by other classes or structs. In addition, they're pass by value, so making
a copy is semantically inherent. To make a copy constructor on a struct,
you can do it like this:

struct MyStruct {
int a;
// lots of different fields goes here
float x;
MyStruct (MyStruct my) {
// create an exact copy of mc here
this = my;
}
}

In struct constructors, the keyword "this" has the semantic similar to an
"out parameter" (if you're familiar with reference/output parameters in
C#). This is documented in the C# specification.

If you're bent on copying all the fields in a class though, you can do it
via Reflection.

using System.Reflecti on;

class MyClass {
int a;
// lots of different fields goes here
float x;

MyClass() {
// default constructor
}

MyClass (MyClass my) {
// create an exact copy of mc here
FieldInfo[] fields = typeof(MyClass) .GetFields(Bind ingFlags.Public
| BindingFlags.No nPublic | BindingFlags.In stance);
foreach(FieldIn fo f in fields) {
f.SetValue(this ,f.GetValue(oth ));
}
}
}

Something like the above should work out for you, if not feel free to reply
to this thread on the newsgroup.

I hope this helps,

--Theo
Theo Yaung
Visual Studio .NET
Microsoft Corp.
--------------------
Reply-To: "Cody Manix" <de********@web .de>
From: "Cody Manix" <de********@web .de>
Subject: cloning objects
Date: Mon, 18 Aug 2003 14:44:28 +0200

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)
{
// create an exact copy of mc here
}
}

normaly, object.MemberWi seClone() would be the way to go but it seems its
useless within a constructor.
is there another way (without copying every item manually)?

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu
[noncommercial and no fucking ads]

--

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which they
originated.

Nov 15 '05 #2

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

Similar topics

4
2455
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?
11
2999
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(),...
8
4861
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
8386
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...
1
2048
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...
10
7597
by: pazabo | last post by:
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; // ... }
1
1722
by: colmkav | last post by:
Hi, what is the main reason why cloning is done to tables in Access VBA code? regards Colm
3
8744
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...
9
13290
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...
0
7911
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...
0
7839
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...
1
7954
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...
0
8215
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...
0
6610
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
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...
0
5390
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...
1
2345
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
0
1179
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...

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.