I have some code which is like follows:
MyClass* a = new MyClass();
vector[0] = *a;
MyClass KeepCopy = vector[0];
//
//
vector gets changed
//
//
return KeepCopy
Now vector then goes and does lots of stuff and gets overridden. However, I wish to return the value of KeepCopy at the end of my function. However, because vector[0] is no pointing to something else I think I am being returned the wrong data.
EDIT3: Ok so this is whats happening. KeepCopy gets assigned to vector[0] and then in the code I do stuff to vector[0]. I was thinking that KeepCopy still points to a version of vector[0], but it appears KeepCopy only contains a copy of the value AT THE TIME which the assignment was made.
Later on I assign vector to another vector object (I am reading a text file two lines at a time, vector contains one line and this other vector object contains the second line). How can I make sure KeepCopy points to the original vector[0] element (before I start parsing through each line in the textfile, reassigning the vectors)?
As you are storing the object by value (and not by pointer/referenence), changes to
vector[0]are not reflected inKeepCopy, unless you share pointers to the same contained object inMyClassinstancesIf this is the case, you should implement a proper copy constructor that makes a deep copy of the original (instead of the default shallow copy that just blindly copies the values of pointers)