[OOP]{POLYNOMIAL} need help PLEASE!! :/

Hi guys so i'm currently working on something and i need help some help. after i wrote this program at first it worked normally but giving me garbage value which is why i should use the operator= but now before adding anything new instead of normally giving me a garbage value it's giving me this breakpoint.

Question: Define a class called polynomial providing the following services:
 Constructor, copy constructor and destructor.
 Overload the following operators: + and -.
 Overload the input operator (>>).
 Overload the output operator (<<) to produce a polynomial P as follows:
P = a0 + a1x + a2x2 + : : : + anxn
 Main function that demonstrates your class capabilities. Do we need to over-
load the operator = to solve this problem?

Here is my program: (i should first do one without an operator= then do it with)

#include<iostream>
using namespace std;

class polynomial {
public:
	int *t, n;
	polynomial();
	polynomial(polynomial& other);
	~polynomial();
	friend ostream& operator<<(ostream& output, polynomial c);
	friend istream& operator>>(istream& input, polynomial& c);
};
polynomial::polynomial(){
	cout<<"please enter a value of n:"<<endl;
	cin>>n;
	t=new int[n];
}
polynomial::polynomial(polynomial& other)
{
	int i;
	n=other.n;
	t=new int[n];
	for(i=0; i<n; i++)
		t[i] = other.t[i];
}

polynomial::~polynomial()
{
	delete []t;
}
polynomial operator-(polynomial c1, polynomial c2)
{
	int i;
	polynomial result;
	for(i=0;i<c1.n;i++)
	result.t[i] = c1.t[i] - c2.t[i];
	return result;
}

polynomial operator+(polynomial c1, polynomial c2)
{
	polynomial result;
	int i;
	for(i=0;i<c1.n;i++)
	result.t[i] = c1.t[i] + c2.t[i];
	return result;
}

istream& operator>>(istream& input, polynomial& c)
{
	int i;
	i=0;
	cout<<"Please enter the above values:"<<endl;
	for(i=0;i<c.n-1;i++)
		input>>c.t[i];

	return input;
}
ostream& operator<<(ostream& output, polynomial c)
{
	int i;

	output<<" P= "<<c.t[0];
	
	for(i=1;i<c.n;i++)
		output<<" + "<<c.t[i]<<"x^ "<<i;

	return output;
}


int main() {
	polynomial x, y, z;

	cin>>x>>y;

	z=x+y;


	cout<<z;

	system("pause");
		return 0;
}
Last edited on
Guys!! nevermind it got solved anyways here is the changes i have done.
#include<iostream>
using namespace std;

void polynomial::operator=(const polynomial &poly)
{
n = poly.n;

for(int i = 0; i < n; i++)
t[i] = poly.t[i];
}

polynomial operator-(polynomial c1, polynomial c2)
{
polynomial result;
if(c1.n > c2.n)
result.n = c1.n;
else
result.n = c2.n;

result.t=new int[result.n];

int i;
for(i=0;i<result.n;i++)
result.t[i] = c1.t[i] - c2.t[i];
return result;
}

polynomial operator+(polynomial c1, polynomial c2)
{
polynomial result;
if(c1.n > c2.n)
result.n = c1.n;
else
result.n = c2.n;

result.t=new int[result.n];

int i;
for(i=0;i<result.n;i++)
result.t[i] = c1.t[i] + c2.t[i];
return result;
}
Topic archived. No new replies allowed.