title: How to access a variable that is out of scope?
body: <pre><code>class foo{
      vector&lt;foo*&gt;* queue;
      vector&lt;int&gt; pos;
      foo(vector&lt;foo*&gt;* queue, vector&lt;int&gt; pos){
          this-&gt;queue=queue;
          this-&gt;pos=pos;
      }
  public:
      foo(vector&lt;foo*&gt;* queue){
          this-&gt;queue=queue;
      }
      void init(){
          vector&lt;int&gt; posNew = pos;
          //Create Binary Tree Children of the state FOO
          posNew.push_back(/* An Additional Value*/)
          foo newFoo(queue, posNew);
          queue-&gt;push_back(&amp;newFoo);
      }//Here the variables newFoo and posNew are out of scope so they are deleted even from the queue
  }
  
  class bar{
      vector&lt;foo*&gt; queue; //Assume that queue has a root node added to it.
      bar(){
          for(unsigned int i=0; i&lt;queue.size();i++){
              queue[i]-&gt;init();// Somewhere along when the third element is calculated the value overflows since I assume the object are deleted
          }
      }
  }
  </code></pre>
  
  <p>I am trying to use BFS search with a queue to solve a problem. However I am not able to get the queue to work since the object child object I create are going out of scope. Any help of this would be appreciated.</p>
  
  <p><strong>EDIT:</strong>
  In my actual code, I am having trouble since when the object goes out of scope it shows me these memory allocations.
  <a href="https://i.stack.imgur.com/HBaSD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HBaSD.png" alt="enter image description here"></a></p>
  
  <p>This green part is where the root node is, the red part is where the expected data for the child nodes was supposed to be but its now deleted.</p>