I'm learning cpp and I've tried to always allocate memory correctly but now after adding deconstructor, it crashes with HEAP CORRUPTION DETECTED. I want to be able to have W1 smaller than W2. Right now, program works (without destructor ofc) if W1 is bigger than W2, but otherwise it cuts result up to the W1 size. I use Visual Studio 2019. Here is my code:
#include <iostream>
using namespace std;
class Polynomial
{
private:
int degree_;
int* ptr= nullptr;
public:
Polynomial()
{
int* ptr = new int[1];
ptr[0] = 0;
}
Polynomial(int degree)
{
degree_ = degree;
ptr = new int[degree_ + 1]; //+1 for the coefficient next to x^0
}
Polynomial(const Polynomial& oldobj)
{
degree_ = oldobj.degree_;
ptr = new int[degree_ + 1];
*this = oldobj;
//for (int i = 0; i < degree + 1; i++)
//ptr[i] = oldobj.ptr[i];
}
~Polynomial()
{
delete[]ptr;
}
Polynomial& operator+(const Polynomial& tempobj)
{
for (int i = 0; i <= tempobj.degree_; i++)
{
ptr[i] += tempobj.ptr[i];
}
return *this;
}
Polynomial& operator=(const Polynomial& tempobj)
{
degree_ = tempobj.degree_;
ptr = tempobj.ptr;
return *this;
}
friend istream& operator>>(istream& in, Polynomial& obj);
friend ostream& operator<<(ostream& oou, const Polynomial& obj);
};
istream& operator>>(istream& in, Polynomial& obj)
{
for (int i = obj.degree_; i >= 0; i--)
{
if (i == 0)
{
cout << "Last Coefficient: ";
cin >> obj.ptr[i];
break;
}
cout << "Coefficient in x^" << i << ": ";
cin >> obj.ptr[i];
}
return in;
}
ostream& operator<<(ostream& out, const Polynomial& obj)
{
cout << "f(x)= ";
for (int i = obj.degree_; i >= 0; i--)
{
cout << obj.ptr[i] << "x^" << i << " ";
}
return out;
}
int main()
{
Polynomial W1(2), W2(4), W3; //I want W1 to be able to swap places with W2.
//Right now it works only when W2 is smaller than W1;
cin >> W1;
cout << endl << W1<<endl;
cin >> W2;
cout << endl << W2 << endl;
W3 = W1 + W2;
cout << endl << W3;
return 0;
}
So first, how can I fix the destructor? Thanks for your time.