title: Putting derived classes into STL maps as values
body: <p>I have 2 simple classes. Base class <code>A</code>, and a derived class <code>B</code>. For debugging purposes, copy constructor and destructor are overridden to <code>cout</code> stuff:</p>
  
  <pre><code>class A
  {
  protected:
      char * c;
  public:
      A(char * c) : c(c) { cout &lt;&lt; "+A " &lt;&lt; this &lt;&lt; "\n"; }
      A(const A&amp; other) : c(other.c) { cout &lt;&lt; "*A " &lt;&lt; this &lt;&lt; "\n"; }
      ~A() { cout &lt;&lt; "-A " &lt;&lt; this &lt;&lt; "\n"; }
  };
  
  class B : public A
  {
  public:
      B(char * c) : A(c) { cout &lt;&lt; "+B " &lt;&lt; this &lt;&lt; "\n"; }
      B(const B&amp; other) : A(other.c) { cout &lt;&lt; "*B " &lt;&lt; this &lt;&lt; "\n"; }
      ~B() { cout &lt;&lt; "-B " &lt;&lt; this &lt;&lt; "\n"; }
  };
  </code></pre>
  
  <p>Here's how I <code>insert</code> an instance of <code>B</code> into the <code>map</code>:</p>
  
  <pre><code>    {
          cout &lt;&lt; "-- 1\n";
          map&lt;string, A&gt; m;
          cout &lt;&lt; "-- 2\n";
          m.insert(pair&lt;string, A&gt;( "b", B("bVal")));
          cout &lt;&lt; "-- 3\n";
      }
      cout &lt;&lt; "-- 4 --\n";
  </code></pre>
  
  <p>The result of that:</p>
  
  <pre><code>-- 1
  -- 2
  +A 0051F620
  +B 0051F620
  *A 0051F5EC
  *A 00BD8BAC
  -A 0051F5EC
  -B 0051F620
  -A 0051F620
  -- 3
  -A 00BD8BAC
  -- 4 --
  </code></pre>
  
  <p>As regards creation of instances, I read this as follows:</p>
  
  <ol>
  <li><code>B</code> gets created by my own code</li>
  <li>that <code>B</code> gets copy-constructed into an <code>A</code> by <code>pair</code></li>
  <li>that last <code>A</code> instance then gets copied once more by the <code>map</code>, where it is inserted</li>
  </ol>
  
  <p>Btw changing the <code>pair</code> in the <code>insert</code> line to a <code>pair&lt;string, B&gt;</code> did not do the trick, it only changed the 2nd step to create an <code>B</code> instead of the <code>A</code>, but the last step would <em>downgrade</em> it to an <code>A</code> again. The only instance in the map that remains until the map itself is eligible for destruction seems to be that last <code>A</code> instance.</p>
  
  <p>What am I doing wrong and how am I supposed to get a derived class into a map? Use maps of the format</p>
  
  <pre><code>map&lt;string, A*&gt;
  </code></pre>
  
  <p>perhaps?</p>
  
  <p><strong>Update - Solution</strong> As my solution is not stated directly in the accepted answer, but rather buried in its comments in form of suggestions, here's what I ended up doing:</p>
  
  <pre><code>map&lt;string, shared_ptr&lt;A&gt;&gt; m;
  </code></pre>
  
  <p>This assumes your build environment supports <code>shared_ptr</code>s - which mine (C++/CLI, Visual Studio 2010) does.</p>