title: polymorphic C++ references
body: <p>I was wondering <strong>how</strong> you can do polymorphism with references, as opposed to pointers.</p>
  <p>To clarify, see the following minimal example:</p>
  <pre><code>class A;
  
  class B {
    public:
      A&amp; a; ///////////////// &lt;- #1
      B();
      void doStuff();
  };
  
  class A {
    public:
      virtual void doSmth() = 0;
  };
  void B::doStuff() {
    a.doSmth();
  }
  
  class A1 : public A {
    public:
      void doSmth() {
      }
  };
  
  B::B() : a(
      *        ////////////// &lt;- #2
        (new A1)  /////////// &lt;- #3
       ) {
  }
  </code></pre>
  <p>This compiles and works, but as the most important point here is that <code>a</code> in line <code>#1</code> is a reference, so in order to be able to use it polymorphically (is that an actual word?), as shown in line <code>#3</code> I have to &quot;convert a pointer to a reference&quot; by dereferencing it.</p>
  <p>This strikes me as a bit odd, and I was wondering if there is a better (in the sense of <em>cleaner</em>) way. Is it just me?</p>
  <h3>Rationale</h3>
  <p>It would be great if I didn't need a <code>new</code> at all, but when declaring (!) <code>B</code> I have no clue how to create an instance of <code>A1</code> (!) as <code>A</code> is a forward declaration -- <code>A1</code> is implemented in the same compilation unit as <code>B</code>. Still, is there a real need for dynamic memory allocation in this case? How would you do this?</p>
  <p>Sorry for the slightly twofold question.</p>
  <h2>Edit</h2>
  <p>Note: <code>B</code> is huge (and I cannot make a template class of it), and will go out of scope precisely when the program terminates -- <code>a</code> is small and makes two big modules talk to each other, it will be needed as long as the instance of <code>B</code> lives (there is only one).</p>
  <h2>Edit 2</h2>
  <p>I just realised, that since both <code>A</code> and <code>B</code> are effectively singletons, I can simply create a <code>static</code> instance of <code>A1</code> in the compilation unit of <code>B</code>, avoiding dynamic memory allocation (even if there were two <code>B</code>s they could easily use the same instance of <code>A</code>). To be fair, I did not post this as answer, but will accept the answer that prompted me to come up with this <em>solution</em>.</p>