title: How do I implement polymorphism with std::shared_ptr?
body: <p><em>I have seen some of the other questions on this topic, but have still not found the answer - I guess I'm missing something:</em></p>
  
  <p>I defined two simple test classes:</p>
  
  <pre><code>class TestBase
  {
  
    public:
  
      TestBase ( ) { };
      ~ TestBase ( ) { };
  
    protected:
  
      inline virtual int getInt ( )
      {
          return 0;
      }
  
  };
  
  class TestDerived : public TestBase
  {
  
    protected:
  
      inline int getInt ( ) override
      {
          return 1;
      }
  
  };
  </code></pre>
  
  <p>I declared typedefs to simplify their usage with <code>std::shared_ptr:</code></p>
  
  <pre><code>typedef std::shared_ptr&lt;TestBase&gt; spBase;
  typedef std::shared_ptr&lt;TestDerived&gt; spDerived;
  </code></pre>
  
  <p>Problem: I cannot compile code to use these <code>shared_ptr</code> declarations polymorphically, even though <code>base</code> in all these cases is actually an instance of <code>spDerived</code>:</p>
  
  <blockquote>
  <pre><code>spBase base;
  spDerived derived = static_cast &lt; spDerived &gt; ( base );
  </code></pre>
    
    <p><strong><em>error: no matching function for call to ‘std::shared_ptr::shared_ptr(spBase&amp;)</em></strong></p>
  
  <pre><code>spDerived derived = dynamic_cast &lt; spDerived &gt; ( base );
  </code></pre>
    
    <p><strong><em>error: cannot dynamic_cast ‘base’ (of type ‘spBase {aka class std::shared_ptr}’) to type ‘spDerived {aka class
    std::shared_ptr}’ (target is not pointer or reference)</em></strong></p>
  
  <pre><code>spDerived derived = static_pointer_cast &lt; spDerived &gt; ( base );
  </code></pre>
    
    <p><strong><em>error: conversion from ‘std::shared_ptr >’ to non-scalar type
    ‘spDerived {aka std::shared_ptr}’ requested</em></strong></p>
  
  <pre><code>spDerived derived = dynamic_pointer_cast &lt; spDerived &gt; ( base );
  </code></pre>
    
    <p><strong><em>error: conversion from ‘std::shared_ptr >’ to non-scalar type
    ‘spDerived {aka std::shared_ptr}’ requested</em></strong></p>
  </blockquote>
  
  <p>I'm using C++11 on an Ubuntu 14.04 box with the default GCC tool chain. Compiler is gcc-4.9.
  What am I doing wrong? Can't a shared_pointer be used polymorphically?</p>