object references
-
Hi, i have two object of same class, suppose object name are class1 and class2. and i have made class1 object and assign it to class2 object.if i do make chages in class2 then it also affact to class2 object. but i dont want this.means if i make any changes in class2 then it should not affact to class1 object. so for thos what should i do. please help.
amit
-
Hi, i have two object of same class, suppose object name are class1 and class2. and i have made class1 object and assign it to class2 object.if i do make chages in class2 then it also affact to class2 object. but i dont want this.means if i make any changes in class2 then it should not affact to class1 object. so for thos what should i do. please help.
amit
First, calling an object class1 or class2 is a bad idea. Second, when you say
obj1 = obj2;
with reference types, you are not assigning one object to another, you are only assigning a reference to another.amit_83 wrote:
if i do make chages in class2 then it also affact to class2 object.
Yes.
amit_83 wrote:
but i dont want this.means if i make any changes in class2 then it should not affact to class1 object.
1. Don't assign the references. 2. If you absolutely must do something of the sort, consider implementing your
Clone()
method which creates a new object.Cheers, Vikram.
"I will put my new found knolage to good use" - Captain See Sharp. "Every time Lotus Notes starts up, somewhere a puppy, a kitten, a lamb, and a baby seal are killed." - Gary Wheeler.
-
Hi, i have two object of same class, suppose object name are class1 and class2. and i have made class1 object and assign it to class2 object.if i do make chages in class2 then it also affact to class2 object. but i dont want this.means if i make any changes in class2 then it should not affact to class1 object. so for thos what should i do. please help.
amit
Well it's confusing at start but try to think of all "class"-objects as POINTERS or references (in C++). You've got several possible solutions: 1.) Implement something like Clone (like proposed) - normaly you just add an copy-constructor so you can say
MyClass Obj2 = new MyClass(Obj1)
and use this in the Clone()-implementation - this way you can save one cast 2.) use struct instead of class - this will locate your objects in the local stack and copy the data instead of the reference when you say (obj2 = obj1) 3.) use the same data to construct the object 2 times with new etc.