title: C++ base class reference initialize with different derived class object
body: <pre class="lang-c prettyprint-override"><code>class Base
  {
  public:
      void operator()() { func(); }
  private:
      virtual void func() {}
  };
  
  class Derived1 : public Base
  {
  private:
      void func() override {/*do something*/}
  };
  
  class Derived2 : public Base
  {
  private:
      void func() override {/*do something else*/}
  };
  </code></pre>
  
  <p>Because I want to use operator overloading,<br>
  Reference is a better option than pointer.</p>
  
  <p>What I intend to do is like:
  </p>
  
  <pre><code>if (condition) {
      Base&amp; obj = Derived1();
  } else {
      Base&amp; obj = Derived2();
  }
  </code></pre>
  
  <p>But obj will be destroyed and end of scope.
  </p>
  
  <pre><code>Base&amp; obj;
  if (condition) {
      obj = Derived1();
  } else {
      obj = Derived2();
  }
  </code></pre>
  
  <p>Will not work either,<br>
  Because reference need to be initialized on declaration.</p>
  
  <p>If I try:
  </p>
  
  <pre><code>Base&amp; obj = condition ?
      Derived1() : Derived2();
  </code></pre>
  
  <p>Still an error,
  Because ternary operator expect convertible type.</p>
  
  <p>What is the best solution to deal with this problem?</p>