I've created a class which can add two polynomial coefficients, which are simply the numbers in a dynamic array index positions. My main issue is with the overload+ function return value. Once I add two objects of the same class, the Visal Studio will give me an error if I try to return an object variable, but if I return the constructor to an object, then the code works fine, and there is no error. I don't know why I get this error, as in my previous assignments on dynamic arrays, I was returning object variables without any problems? I'm not sure what are the rules on return values for the operator+ overload function in this case? Thanks.
#include <iostream>
#include <vector>
using namespace std;
class polynomial
{
public:
polynomial();
polynomial(vector<double> vec);
polynomial(const polynomial& obj);
void get();
polynomial& operator=(const polynomial& rightSide);
friend const polynomial operator +(const polynomial& x, const polynomial& y);
//The function in question
~polynomial() { delete[] p; };
private:
double *p;
int expSize;
};
int main()
{
vector<double> x(3);
vector<double>y(3);
x = { 2,3,4 };
y = { 4,3,2 };
polynomial X(x); //<-- Both objects are constructed with vectors
polynomial Y(y);
polynomial obj;
obj = X + Y; //<-- Adding dynamic arrays, and saving the values in obj.
obj.get();
cout << endl;
system("pause");
return 0;
}
polynomial::polynomial()
{
expSize = 3;
p = new double[expSize];
for (int c = 0; c < expSize; c++)
p[c] = 0;
}
polynomial::polynomial(vector<double>vec)
{
expSize = vec.size();
p = new double[expSize];
for (int c = 0; c < expSize; c++)
p[c] = 0;
for (int c = 0; c < expSize; c++)
p[c] = vec[c];
}
polynomial::polynomial(const polynomial& obj)
{
p = new double[expSize];
for (int c = 0; c < expSize; c++)
p[c] = obj.p[c];
}
polynomial& polynomial::operator=(const polynomial& rightSide)
{
if (this == &rightSide)
return *this;
else
{
expSize = rightSide.expSize;
delete[] p;
p = new double[expSize];
for (int c = 0; c < expSize; c++)
p[c] = rightSide.p[c];
return *this;
}
}
const polynomial operator +(const polynomial& x, const polynomial& y)
{
polynomial obj;
if (x.expSize > y.expSize) //<-- obj.expSize private member variable will
obj.expSize = x.expSize; // inherit the larger dynamic array index size
else if(x.expSize <= y.expSize) // of the two parameter objects.
obj.expSize = y.expSize;
for (int c = 0; c < obj.expSize; c++) {
obj.p[c] = x.p[c] + y.p[c];
}
vector<double>vec(obj.expSize); //<-- Vector will inherit the new index size too.
for (int c = 0; c < obj.expSize; c++) {
vec[c] = obj.p[c]; //<-- Vector takes joined values of two objects
}
//return polynomial(vec); //<-- Returning a constructor with vector works fine
return obj; //<-- abort() has been called error
}
void polynomial::get()
{
for (int c = 0; c < expSize; c++)
cout << p[c] << endl;
}