title: Generic object for derived classes for instantiation and returning purposes
body: <p>I want to create a graph object which can switch between following different mathematical functions as I plot along it. I am currently keeping the current math function as an object inside the graph object, so it knows what to follow when I call its plotting function, and am trying to use polymorphism to describe different kinds of math functions. My current (non-working) code looks like this:</p>
  <pre><code>#pragma once
  #include&lt;array&gt;
  
  class MathExpression
  {
  public:
      virtual ~MathExpression() = default;
      virtual MathExpression integrate() const = 0;
  };
  
  class Polynomial : public MathExpression
  {
  public:
      Polynomial(std::array&lt;double, 5&gt; coefficients) : coefficients(coefficients) {};
      Polynomial() : coefficients(std::array&lt;double, 5&gt;{0.0, 0.0, 0.0, 0.0, 0.0}) {};
      Polynomial(const Polynomial&amp; p) : coefficients(p.coefficients) {};
      ~Polynomial() = default;
  
      Polynomial integrate() const;
      std::array&lt;double, 5&gt; getCoefficients() const;
  private:
      std::array&lt;double, 5&gt; coefficients;
  };
  
  class Exponential : public MathExpression
  {
  public:
      Exponential(std::array&lt;double, 3&gt; coefficients) : coefficients(coefficients) {};
      Exponential() : coefficients(std::array&lt;double, 3&gt;{0.0, 0.0, 0.0}) {};
      Exponential(const Exponential&amp; e) : coefficients(e.coefficients) {};
      ~Exponential() = default;
  
      Exponential integrate() const;
      std::array&lt;double, 3&gt; getCoefficients() const;
  private:
      const std::array&lt;double, 3&gt; coefficients;
  };
  
  class Graph
  {
  public:
      Graph() = default;
      MathExpression getCurrentCurve() {return current_curve;}
      void setCurrentCurve(const MathExpression&amp; curve) {
          current_curve = curve;
          return;
      }
  private:
      MathExpression current_curve;
  };
  </code></pre>
  <p>This code does not work as mathExpression is an abstract class which contains pure virtual functions and therefore I can neither create instances of it, nor return it from functions. I am also getting errors from the integrate() functions of the derived classes that the return type (Polynomial/Exponential) is not identical to nor covariant with the return type MathExpression of the overridden integrate() function.</p>
  <p>I need to find a solution to these two problems:</p>
  <ul>
  <li>How to have a generic member in Graph which could be any derived class of mathExpression and which can be redefined at will, even to other derived classes (going from a polynomial to exponential, for example).</li>
  <li>How to return that derived class type from member functions inside Graph or the derived classes (such as getCurrentCurve() or integrate()).</li>
  </ul>
  <p>How can I solve this/work around these issues?</p>