title: Call to virtual function cause Segmentation Fault in C++
body: <p>I am having a problem with a simple math analysis tool I am developing in C++,<br>
  specifically the program cause Segmentation Fault at a certain point during execution. Here is a<br>
  simplified version of the code:  </p>
  
  <pre><code>#include &lt;string&gt;
  
  using namespace std;
  
  class Function 
  {
  
  string equation;
  
  public: 
      Function(string equation) { this-&gt;equation = equation; }
      virtual string derivative() 
      { 
          // throws exception since it 
          // should never be invoked on Function 
      }
  };
  
  class Polynomial : public Function
  {
  
  public:
      Polynomial(string equation) : Function(equation);
      string derivative() { //compute the derivative }
  };
  
  class Exponential : public Function
  {
  
  public:
      Exponential(string equation) : Function(equation);
      string derivative() { //compute the derivative }
  };
  
  ...
  
  class Logarithmic : public Function
  {
  
  public:
      Logarithmic(string equation) : Function(equation);
      string derivative() { //compute the derivative }
  };
  
  int main(int argc, char * argv)
  {
      string equation = argv;
      Function *f;
      if (//some condition)
          f = new Polynomial();
      else if (//some condition)
          f = new Exponential();
      ...
  
      else if (//some condition)
          f = new Logarithmic();
  
      string der = f-&gt;derivative();
  }  
  </code></pre>
  
  <p>My guess is that the problem is caused by the pointer <code>*f</code>  losing the assigned value after<br>
  the if-statement (by initializing it to <code>Function *f = new Function();</code> I get an<br>
  exception instead of a SegFault, meaning that it calls the method in the parent class).<br>
  In case it may help, I am working in a QT environment on a Ubuntu 13.10 machine.<br>
  Can someone help me fix this or suggest an alternative pattern? Thanks </p>