title: Keep object and reference to an object created inside a function
body: <p>I'm new to C++ so still learning about pointers and getting used to using them.</p>
  
  <p>I have declared an object map in order to store objects that the user might access later on using the tag key.</p>
  
  <pre><code>map&lt;string,MyObject*&gt; myMap;
  </code></pre>
  
  <p>The objects I'm adding to myMap are created in a function called by my main</p>
  
  <pre><code>void myFunction(){
      ...
      MyObject obj1();
      MyObject* objPtr;
      objPtr = &amp;obj1;
      myMap.insert(pair&lt;string,MyObject*&gt;("xxxx", objPtr));
      ...
      } 
  </code></pre>
  
  <p>When I execute this function the object pointer is perfectly inserted to myMap, but after the function execution I lose the reference to obj1 I guess because the pointer and the object were created locally inside the function, so I still have an element "xxx" in the map but with what I think is an empty reference after.</p>
  
  <p>How can I keep the object and the reference globally? I wanted to create this object in the function since it has some variable parameters that needs to get from a user obj1(m,n). Thanks for any help.</p>