title: unique_ptr and polymorphism
body: <p>I have some code that currently uses raw pointers, and I want to change to smart pointers. This helps cleanup the code in various ways. Anyway, I have factory methods that return objects and its the caller's responsibility to manager them. Ownership isn't shared and so I figure <code>unique_ptr</code> would be suitable. The objects I return generally all derive from a single base class, <code>Object</code>.</p>
  
  <p>For example,</p>
  
  <pre><code>class Object { ... };
  class Number : public Object { ... };
  class String : public Object { ... };
  
  std::unique_ptr&lt;Number&gt; State::NewNumber(double value)
      {
          return std::unique_ptr&lt;Number&gt;(new Number(this, value));
      }
  
  std::unique_ptr&lt;String&gt; State::NewString(const char* value)
      {
          return std::unique_ptr&lt;String&gt;(new String(this, value));
      }
  </code></pre>
  
  <p>The objects returned quite often need to be passed to another function, which operates on objects of type <code>Object</code> (the base class). Without any smart pointers the code is like this.</p>
  
  <pre><code>void Push(const Object* object) { ... } // push simply pushes the value contained by object onto a stack, which makes a copy of the value
  Number* number = NewNumber(5);
  Push(number);
  </code></pre>
  
  <p>When converting this code to use <code>unique_ptrs</code> I've run into issues with polymorphism. Initially I decided to simply change the definition of <code>Push</code> to use <code>unique_ptrs</code> too, but this generates compile errors when trying to use derived types. I could allocate objects as the base type, like</p>
  
  <pre><code>std::unique_ptr&lt;Object&gt; number = NewNumber(5);
  </code></pre>
  
  <p>and pass those to <code>Push</code> - which of course works. However I often need to call methods on the derived type. In the end I decided to make <code>Push</code> operate on a pointer to the object stored by the <code>unique_ptr</code>. </p>
  
  <pre><code>void Push(const Object* object) { ... }
  std::unique_ptr&lt;Object&gt; number = NewNumber(5);
  Push(number.get());
  </code></pre>
  
  <p>Now, to the reason for posting. I'm wanting to know if this is the normal way to solve the problem I had? Is it better to have <code>Push</code> operate on the <code>unique_ptr</code> vs the object itself?  If so how does one solve the polymorphism issues? I would assume that simply casting the ptrs wouldn't work. Is it common to need to get the underlying pointer from a smart pointer?</p>
  
  <p>Thanks, sorry if the question isn't clear (just let me know).</p>
  
  <p>edit: I think my Push function was a bit ambiguous. It makes a copy of the underlying value and doesn't actually modify, nor store, the input object.</p>