My intention is to store a list of B objects in class A, but I want a new element to be created in A list when I call B constructor.
I have a code like this:
class A
{...
protected:
std::list<B> Blist;
std::list<B>::iterator Bit;
...
public:
Update();
...
friend class B;
}
class B
{...
protected:
A* p_A;
...
public:
B(); //Standard constructor
B(A* pa); // This is the constructor I normally use
}
B::B(A* pa)
{
p_A=pa; // p_A Initialization
p_A->Bit = p_A->Blist.insert(p_A->Blist.end(), *this);
}
A::Update()
{
for(Bit=Blist.begin(); Bit != Blist.end(); Bit++)
{
(*Bit).Draw() //Unrelated code
}
}
void main() //For the sake of clarity
{
A* Aclass = new A;
B* Bclass = new B(A);
Aclass.Update(); // Here is where something goes wrong; current elements on the list are zeroed and data missed
}
Well, the program compile with no difficulty, but when I run the program I don't get the desired result.
For B I have two constructors, a default one which zeroize everything and another which accepts inputs to initialize internal variables.
When I use the second to initialize private variables, then during A.Update method, everything is zeroed and looks like I would have used default constructor instead.
Am I doing something wrong? Is my approach correct?
Thanks you!
EDIT: PROGRAM EDITED FOR CLARITY