title: how to return an abstract class using c++
body: <p>Been running into a snag while working in C++. I've tried several answers on SO, as well as other places (like: <a href="https://stackoverflow.com/questions/2861270/returning-an-abstract-class-from-a-function">returning an abstract class from a function</a>, and <a href="https://stackoverflow.com/questions/3327307/how-do-i-make-an-abstract-class-properly-return-a-concrete-instance-of-another-a">How do I make an abstract class properly return a concrete instance of another abstract class?</a>), but I've still been having trouble-- these don't seem to completely fit...</p>
  
  <p>I have an abstract class, a derived class:</p>
  
  <pre><code>class AbstractClass {
      virtual std::string virtMethod() = 0;
  }
  
  class Derived : public AbstractClass {
      std::string virtMethod();
  }
  </code></pre>
  
  <p>Also, I a separate class which I'm trying to get a return type of the abstract class (of course, returning an instance of the derived class).</p>
  
  <p>I've tried using pointer and reference:</p>
  
  <pre><code>AbstractClass* methodFromOtherClass() {
      if (somethingIsTrue) {
          Derived d = Derived();
          return &amp;d;
      }
  
      SomeOtherDerived s = SomeOtherDerived();
      return &amp;s;
  }
  </code></pre>
  
  <p>Which, in Xcode, gives me the warning: </p>
  
  <blockquote>
    <p>Address of stack memory associated with local variable 'd' returned</p>
  </blockquote>
  
  <p>I tried creating a static Derived object and was unable to then destroy it in the method which calls my "methodFromOtherClass()."</p>
  
  <p>I've also tried my hand at smart pointers (though someone may point out my obvious misuse of them):</p>
  
  <pre><code>std::unique_ptr&lt;AbstractClass&gt; methodFromOtherClass() {
      if (somethingIsTrue) {
          Derived d = Derived();
          return std::unique_ptr&lt;AstractClass&gt;(&amp;d);
      }
  
      SomeOtherDerived s = SomeOtherDerived();
      return std::unique_ptr&lt;AstractClass&gt;(&amp;s);
  }
  </code></pre>
  
  <p>The above, perhaps unsurprisingly, gives me a segfault.</p>
  
  <p>I'm used to being able to do this easily in Java... Any help would be appreciated. C++ isn't a very strong language for me at the moment, so it could be something very basic which I'm overlooking.</p>