Hi, I have pointer object and i have to assign to another variable ( new object ). But if i change any value in new object should not reflect in old object. I did in the below way, it changes the value.
class Test
{
public:
int num;
};
Test* obj;
obj.num=1;
Test obj_n=*obj;
obj_n.num=2;
Now both object's num have value as 2;
i.e
obj.num // has 2
obj_n.num // has 2
Actually my expected result is,
obj.num - should have value 1
obj_n.num - should have value 2
My actual scenario is different where Test obj is pointer object, so obj should be pointer object. i have given sample scenario.
Test* obj;
obj.num=1; // i guess you meant obj->num
The above does not make sense because you have declared obj to be a pointer to an object of class Test. However it is not pointing to anything. You will first have to dynamically allocate memory as follows:
1 2
Test* obj = new Test(); // creates a new object of type Test on the heap and pointer obj points to it.
obj->num=1;
Also, since you have not explicitly overridden the copy constructor, it is better to create the new object the following way.
1 2
Test obj_n; // new object of type Test created on the stack.
obj_n.num=2;
1.Your first point is correct, i made syntax problem in this post. It should be obj->num=1 and Test* obj=new Test().
2.Actually Test class has multiple public variables. i want to assign that object to another and want to change only one variable's value ie. num. Sorry i missed this point on my question.
class Test
{
public:
int num;
int val;
}
Test* obj = new Test();
obj->num=1;
obj-> val=100;
Test obj_n=*obj;
obj_n.num=2;
Here i want to copy obj and assign to obj_n and change only num variable's value.
Now both object's num have value as 2;
i.e
obj.num // has 2
obj_n.num // has 2
Actually my expected result is,
obj.num - should have value 1
obj_n.num - should have value 2