class B;
class A {
B * pointer2B;
public:
void setPointer2B(B* p_P2B){
pointer2B=p_P2B;
}
};
class B {
vector<A *> vec2A;
public:
void addA(A* p_P2A){
p_P2A->setPointer2B(this);
vec2A.push_back(p_P2A);
}
};
class Z {
public:
vector<A> vecA;
vector<B> vecB;
void foo();
};
Inside Z::foo() there's a cycle in wich an object of type A is added to Z::vecA, then B::addA is called to a member from vecB with &(vecA.back()) as a parameter. After that, when I try to print all Z::vecB elements (and the respective content of B::vec2A elements) the program crashes. My guess is that B::vec2A doesn't contain the right pointers.
I've searched and found somewhere that when adding an object to a vector, the address of the previous elements of that vector would change. If that's right, how can I solve this?
Thanks, tipaye, but no. *(vecA.back()) is not even accepted by the compiler [no operator "*" matches these operands; operands type are: * A].
And &(vecA.back()) returns a A *.
Anyway, is there any container like lists, queues, stacks,... in which the address of the elements won't change upon adding another one?
Apologies, for some reason I saw "back()" and thought "end()" this is what happens when English (or C++) is your third language. Thinking about it though, even end() wouldn't have worked, as that points beyond the end of your collection.