pass a pointer of a class
- by small_potato
Say I have Class1 and Class2 and I want a shallow copy constructor for Class1. Class1 has a member variable, which is a pointer pointing to a Class2 instance. Also I have to be able to change the Class2 ptr is pointing at.
in header file:
class Class1
{
Class2* ptr;
...
}
in source file:
Class1::Class1()
{
ptr = new Class2();
}
......
Class2* Class1::Exchange(Class2* newClass2)
{
Class2* temp;
ptr = newClass2;
return temp;
}
......
Now say
Class1 original;
Class1 shallowCopy(original);
Class2* newClass2 = new Class2();
Class2* oldClass2;
oldClass2 = orignal.Exchange(newClass2);
delete oldClass2;
now I want is associate original.ptr with shallowCopy.ptr, when I implement the shallow copy constructor, how do I make sure these two pointer always point at the same Class2? I mean in the class above, the oldClass2 is deleted, so ptr of shallowCopy is pointing at nothing. If I don't delete oldClass2, ptrs of original and shallowCopy are pointing at different Class2 instance.