Feb 20, 2013 at 2:11pm UTC
I have a class A for a sort of a template.
class A
{
A(){}
A(int n){a = n;}
int a;
}
In main class, I create like this.
A *temClass = new A(10);
A *myClass01 = new A();
A *myclass02 = new A();
and I want to copy tmpClass to myClass01, myClass02.
myClass01 = temClass;
myClass02 = temClass;
When I changed a value, all changed. I mean,
myClass01.a = 100;
then, var a in myClass02 and temClass is all 100.
I think they all refer to same address.
How to copy class??
Feb 20, 2013 at 2:32pm UTC
Instead of assigning objects you are assigning pointers. Use
* myClass01 = * temClass;
* myClass02 = * temClass;
Feb 20, 2013 at 4:30pm UTC
to add to it, when you equate pointers, they begin pointing to the same value. In this case all the three pointers start pointing to the address to which temclass was pointing.
Feb 20, 2013 at 5:59pm UTC
Another way to copy is to use the copy constructor:
A *temClass = new A(10);
A *myClass01 = new A(*temClass);
A *myclass02 = new A(*temClass);
vlads correction does the job too, and will work after construction (unlike the above).
Feb 22, 2013 at 6:09pm UTC
Thanks!!!!!!
Pretty simple!!!