Novice C++ programmer here. Let's say I have a class Outer with a nested class Inner. Inner contains a pointer member, set during construction, to Outer. Outer contains a function AddNewInner() that creates a new Inner pointing to itself and adds it to a vector.
class Outer {
public:
class Inner {
public:
Inner(Outer* outerParent) : mOuterParent(outerParent) {}
Outer* mOuterParent;
}
void AddNewInner() {
Inner newInner(this);
mInnersVec.push_back(newInner);
}
vector<Inner> mInnersVec;
}
This works fine when creating a new instance of Outer and calling AddNewInner() to add Inners to the vector. However, I have run into an issue when I try to create a copy of an instance of Outer: The Outer copy's vector of Inners do not point to the copy (itself), they still point to the original Outer.
Outer outerA;
outerA.AddNewInner();
Outer* ptrA = outerA.mInnersVec[0].mOuterParent; // this points to outerA, good!
Outer outerB = outerA;
Outer* ptrB = outerB.mInnersVec[0].mOuterParent; // this still points to outerA, bad!
I need the vector of Inners in the copy to point to the copy, not the original. What's the best way of accomplishing this, or perhaps is there an alternate way to do the same thing?