I have the following main function, creating a product of coefficients using pointers. It's only a small part of the project, which is used to create polynomials:
#include "header.h"
int main()
{
TermProd x = TermProd( new Coeff(4), new Coeff(8));
x.print(); cout << endl;
x = TermProd( new Coeff(8), new Coeff(15));
x.print(); cout << endl;
return 0;
}
After testing, the overwriting seems to be working. But when I call the print on x, I get a segmentation fault. I have been trying and staring at it for quite a while now, but I can't figure out the real problem. Also my searches didn't result into the right direction so I decided to create a small code-snippet which reproduces the error.
My header.h file looks like:
class Term{
public:
Term(){};
virtual ~Term(){};
virtual Term* clone() const = 0;
virtual void print() const = 0;
};
class Coeff:public Term{
int m_val; //by def: >=0
public:
// Constructor
Coeff();
Coeff(int val = 1):m_val(val)
// Copy constructor
Coeff* clone() const{return new Coeff(this->val());}
// Destructor
~Coeff(){}
// Accessors
int val() const{return m_val;} ;
// Print
void print() const{cout << m_val; }
};
class TermProd:public Term{
TermPtr m_lhs, m_rhs;
public:
// Constructor
TermProd(TermPtr lhs, TermPtr rhs):m_lhs(lhs), m_rhs(rhs){ }
// Copy constructor
TermProd* clone() const
{
return new TermProd(m_lhs->clone(), m_rhs->clone());
}
// Destructor
~TermProd(){ delete m_lhs;delete m_rhs;}
// Accessors
Term* lhs() const { return m_lhs; }
Term* rhs() const { return m_rhs; }
// Print
void print() const
{
cout << "("; m_lhs->print(); cout << '*'; m_rhs->print(); cout << ")";
}
};