pass a pointer of a class
Posted
by small_potato
on Stack Overflow
See other posts from Stack Overflow
or by small_potato
Published on 2010-05-22T00:47:04Z
Indexed on
2010/05/22
0:50 UTC
Read the original article
Hit count: 207
c++
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.
© Stack Overflow or respective owner