Convert pointer object to plain object in c++

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.


Could anyone please guide me.

Thanks
Ravi.
1
2
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;
Hi abhi,
Thanks for reply.

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


Test obj_n=*obj; creates a copy, so modifications to obj_n should not affect the values in *obj.
Hi Zhuge,


Thanks for reply. i tried this, still i'm getting same problem. Do you have any other idea?

Should i apply copy constructor here ?
Last edited on
You will have to show your entire implementation of the class.

Yes, you may have to re-implement the constructors.
Topic archived. No new replies allowed.