0

I have a class object that has a constructor containing input parameters relevant to a product. Once instantiated it's member variables contain result data.

For example:

int parm1 = 1;
int parm2 = 2;

MyClass myclass = new MyClass(parm1, parm2);

The MyClass class makes parm1 and parm2 available as public members.

So now I need to create copies of the myclass object, like:

MyClass myclass1 = myclass;
MyClass myclass2 = myclass;

But setting a member in any instance of these classes sets the value in all 3 copies. For example:

myclass1.parm1 = 10;

Sets myclass.parm1, myclass1.parm1 and myclass2.parm1 all to 10.

I need to be able to do the following:

myclass.parm1 = 3;
myclass1.parm1 = 45;
myclass2.parm1 = 5499;

with none of these effecting the others' settings.

How do I create a copy of the initial class object that allows changing public member values without changing those in the original/other copies?

rwkiii
  • 5,716
  • 18
  • 65
  • 114
  • by setting myclass1 and myclass2 values you are pointing to a single object. instead you need to create two separate objects MyClass myclass1 = new MyClass() ( same for myclass2) variable ) – Christo S. Christov May 23 '17 at 21:32
  • @Hristo But how do I create myclass1 so that it contains all of the data contained in myclass after it was initialized and its public member functions have been called, etc.? I see there is a duplicate notice on my question. I searched for an answer first. Not sure how to search for it - now I know to search for the term 'clone'. ;) – rwkiii May 23 '17 at 21:35
  • you need to do deep cloning on one instance to create a 'perfect clone' that's what deep cloning is all about. – Christo S. Christov May 24 '17 at 14:22

0 Answers0