title: c++ Object parameters: polymorphism, value semantics, object lifetimes?
body: <p>As I make the transition from C# to C++ I get a lot of recommendations to use value semantics where possible.  It's pretty much guaranteed that if I post a question with a pointer anywhere someone will come along and suggest that it should be a value instead.  I'm starting to see the light and I have found a lot of places in my code where I could replace dynamic allocation and pointers with stack allocated variables (and usually references).  So I think I have a grasp on using stack allocated objects and passing them to other functions as references when the object lifetime is longer in the caller than the callee.</p>
  
  <p>However I have a question about passing objects by value when the callee will take ownership.  Take the following example:</p>
  
  <pre><code>class Zoo
  {
    void AddAnimal(Animal animal);
    std::list&lt;Animal&gt; animals_;
  }
  </code></pre>
  
  <p>Typically from a flexibility and unit testing perspective I'd want Animal to be an interface (abstract class in C++) so I can easily send arbitrary animals and mock it out with a mock implementation.</p>
  
  <p>In a pointer implementation client code would be calling this like:</p>
  
  <pre><code>Animal animal = new Lion("Bob");
  myZoo.AddAnimal(animal);
  </code></pre>
  
  <p>Here the client code doesn't really need the animal object.  It's just constructing it temporarily to pass to the method.  So in this case there aren't shared semantics.  So it seems like a good case for value semantics.  However, my understanding is that you can't use Animal as a parameter passed by value because it's an abstract class.</p>
  
  <p>Most of my member functions that don't take primitive types take abstract class parameters.  So what is the C++ method to handle this problem?  (That is how do you program to interfaces in C++ with value semantics?)</p>