I've just started learning CPP, please keep that in mind.
Okay so, I am trying to define my own mathematical library, and in it I'm trying to implement a polynomial class.
#include <cmath>
#include <iostream>
class Polynomial
{
public:
Polynomial(int ord);
~Polynomial();
double* getCoeff(); // returns coefficient array
double valueAt(double xVal); // returns the value of the polynomail at xVal
void setCoeff(); // basic "cin" way to add data
void setCoeff(double* inpCoeff, int ord); // adding data by making a double array first
double minAt(double low, double high);
double minVal(double low, double high);
double maxVal(double low, double high);
double maxAt(double low, double high);
Polynomial derivative(); // returns another polynomial which is a derivative of the previous one
double derivativeAt(double xVal); // value of dervative at a particular value
private:
double* coeff; // the coefficient array, (a_0 + a_1 x + a_2 x^2 +...) this arrat contains all the a_i's
int order; // order of the polynomial
};
Now my int main() function is
#include "Polynomial.h"
#include <iostream>
int main()
{
std::cout << "Vigilant starting..." << std::endl;
Polynomial poly(2);
double arr[] = {
1.0, 2.0, 1.0
};
poly.setCoeff(arr, 2);
std::cout << poly.getCoeff() << std::endl;
std::cout << "Value of polynomial at 1 is" << poly.valueAt(1) << std::endl;
std::cout << "Value of polynomial at 1 is" << poly.valueAt(2) << std::endl;
std::cout << "Value of derivative at 1 is" << poly.derivative().valueAt(1) << std::endl;
std::cout << "Value of derivative at 1 is" << poly.derivative().valueAt(2) << std::endl;
return 0;
}
My expected outcome should be successful execution. The program compiles but ends up spitting out an error after successful execution.
The thread 0x4a8 has exited with code 0 (0x0).
HEAP[Vigilant.exe]: Invalid address specified to RtlValidateHeap( 000001D072020000, 000001D0720330C0 )
Vigilant.exe has triggered a breakpoint.
I have no idea what I did wrong. But I'll attach all the definitions used in the int main().
Polynomial::Polynomial(int ord)
{
order = ord;
int rOrd = order + 1;
coeff = new double[rOrd];
}
Polynomial::~Polynomial()
{
delete[] coeff;
}
void Polynomial::setCoeff(double* inpCoeff, int ord)
{
order = ord;
for (int i = 0; i < ord + 1; i++)
{
*(coeff + i) = *(inpCoeff + i);
}
}
double Polynomial::valueAt(double xVal)
{
double res = 0.0;
for (int i = 0; i < order + 1; i++)
{
res += pow(xVal, i) * *(coeff + i);
}
return res;
}
Polynomial Polynomial::derivative()
{
Polynomial poly(order - 1);
poly.order = order - 1;
for (int i = 0; i < order; i++)
{
*(poly.coeff + i) = *(coeff + i + 1) * (i+1.0);
}
return poly;
}