I tried to write a simple class that represents polynomial in CPP but I have a problem probably with freeing the memory and I can`t find any memory leak. Here is a sample of my code, header:
#pragma once
#include <iostream>
using namespace std;
class wielomian
{
int n;
double* a;
public:
wielomian();
wielomian(int k);
wielomian(int k, double* t);
~wielomian();
wielomian& operator=(const wielomian& a);
friend wielomian operator*(const wielomian& a, const wielomian& b);
friend ostream& operator<<(ostream& out, const wielomian& a);
friend istream& operator>>(istream& in, wielomian& a);
}
Definitions of methods and functions
#include <iostream>
using namespace std;
#include "wielomian.h"
wielomian::wielomian() : n(0)
{
a = new (nothrow) double;
if (!a)
return;
a[0] = 1;
}
wielomian::wielomian(int k) : n(k)
{
a = new (nothrow) double[k + 1];
if (!a)
return;
for (int i = 0; i <= n; i++)
a[i] = 1;
}
wielomian::wielomian(int k, double* t): n(k)
{
a = new (nothrow) double[k + 1];
if (!a)
return;
for (int i = 0; i <= n; i++)
a[i] = t[i];
}
wielomian::~wielomian()
{
delete[] a;
}
wielomian operator*(const wielomian& a, const wielomian& b)
{
wielomian c(a.n + b.n);
for (int i = 0; i <= c.n; i++)
c.a[i] -= 1;
for (int i = 0; i <= a.n; i++)
for (int j = 0; j <= b.n; j++)
c.a[i + j] += b.a[j] * a.a[i];
return c;
}
ostream& operator<<(ostream& out, const wielomian& a)
{
for (int i = 0; i < a.n; i++)
out << a.a[a.n - i] << "x^" << a.n - i << "+";
out << a.a[0] << endl;
return out;
}
istream& operator>>(istream& in, wielomian& a)
{
int p;
cin >> p;
a.n = p;
delete[] a.a;
a.a = new (nothrow) double[p + 1];
if (!a.a)
cout << "Problem with memory allocation" << endl;
for (int i = 0; i <= a.n; i++)
{
cin >> p;
a.a[i] = p;
}
return cin;
}
wielomian& wielomian::operator=(const wielomian& b)
{
if (n != b.n)
{
delete[] a;
a = new (nothrow) double[b.n+1];
if (!a)
cout << "Problem with memory allocation" << endl;
n = b.n;
}
for (int i = 0; i <= b.n; i++)
a[i] = b.a[i];
return *this;
}
and finally main:
#include <iostream>
using namespace std;
#include "wielomian.h"
int main()
{
double z[4] = { 1,2,3,4 };
wielomian p, a(2), x(3, z);
cout << p << x << a << endl;
wielomian e;
e = a * x;
cout << e << endl;
}
When the destructor is commented out everything is working fine so that is why im guessing there is a problem with memory allocation. If someone can spot any mistake in my code I would be more than happy. Thanks in advance
EDIT: Problem is solved thanks to your answers, I completely forgot about copy constructor and also delete[] wasnt working for polynomials with one element. Thank you :)