title: Storing an object of a derived class in a reference to the base class
body: <p>I've always worked with pointers and avoided references because I didn't understand how to work with them very well. Today I was working on a small project and decided to use references instead and ran into some behavior I'm not sure how to work around. Basically I have a factory (Factory) that creates either an object of type B or C, both of which are derived from A.</p>
  
  <pre><code>class Factory
  {
  public:
      void create(A&amp; container, int a) //This is for creating an object of B
      {
          B result;
          result.Func(a);
          container = result;
      }
      void create(A&amp; container, int a, int b) //This is for creating an object of C
      {
          C result;
          result.Func(a, b);
          container = result;
      }   
  }
  
  class A
  {
  public:
      virtual void Func(int a) //This is used for an object of B
      {
          var1 = a;
      }; 
      virtual void Func(int, int) {}; // This is used for an object of C
  
  private:
      int var1;
  }
  
  class B : public A
  {
      //Relies of base class Func to set the variable var1;
  }
  
  class C : public A
  {
  public:
      void Func(int a, int b)
      {
          A::Func(int a)
          var2 = a1;
      }
  
  private:
      int var2;
  }
  </code></pre>
  
  <p>The issue arises when I try to do the following</p>
  
  <pre><code>Factory factory;
  A a;
  factory.create(a, 1); //Works fine because B and A have only 1 variable
  factory.create(a, 1, 1); //a only contains A part of C
  </code></pre>
  
  <p>When I check the debugger, there is no sign of var2 to in a after the 2nd create call. I understand its because I'm using a reference to the base type of C and only the A part of C gets stored in the container, but is there a workaround? I know I can just switch A to A*, but I'm interested if there is a non-pointer based solution.</p>
  
  <p>TL;DR
  Is there a way to store an object of a derived class in a reference of the base class without using pointers?</p>