a shallow copy constructor

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:

1
2
3
4
5
class Class1
{
    Class2* ptr;
    ...
}


in source file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Class1::Class1()
{
    ptr = new Class2();
}

......

Class2* Class1::Exchange(Class2* newClass2)
{
    Class2* temp;
    ptr = newClass2;
    return temp;
}

......


Now say

1
2
3
4
5
6
7
8
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.

Last edited on
One way to do it is to add a list<Class1*> member to Class2, which will hold the addresses of the Class1 objects whose ptr points to a particular Class2 object. push_back new elements here whenever you assign the address of a Class2 object to a Class1::ptr, and erase them when you release the association. Also, modify your Exchange function so that it changes the ptr member for every Class1 object whose ptr points to the Class2 object that is going to be changed.
Last edited on
I suppose an alternative would be to make the class2 pointer independent of the class1 - something along the lines of:

1
2
3
4
5
6
7
8
9
10
11
12
Class2 *ptrClass2 = new Class2; //independent Class2 pointer

class Class1
{
    Class2** ptr;
    ...
};

Class1::Class1()
{
    ptr = &ptrClass2;
}


That way you could change/uipdate the class2 pointer directly and all class1's will be affected.
Or you could do something like this and all other class1 objects will be affected
1
2
3
4
5
void  Class1::Exchange(Class2* newClass2)
{
    delete *ptr;
    *ptr = newClass2;
 }


EDIT After re-reading the original question - I don't think my soluion is what the OP is after.
All I've done is created the equivalent of a static variable and the OP only wanted those objects which were copy constructed from each other to have the same pointer.
Last edited on
Topic archived. No new replies allowed.