### Polynomial class help

Hi Guys,

I have a small issue with my code, but can't figure it out. When I call the overloaded operator+, everything is working well until i hit the return statement,which returns some garbage values. Can someone tell me what I am doing wrong please. I suspect it's something to do with the constructors.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117`` `````` #include #define MAX 1000 class Poly{ public: Poly(); Poly(int); ~Poly(); Poly(const Poly&); int getSize()const; void setSize(const int); friend std::istream& operator>>(std::istream&,Poly&); friend std::ostream& operator<<(std::ostream&,Poly&); friend Poly operator+(const Poly&, const Poly&); private: double *arr; int size; }; Poly::Poly(){ arr=new double[MAX]; size=0; } Poly::Poly(int the_size){ arr=new double[the_size]; size=the_size; } Poly::~Poly(){ delete [] arr; } Poly::Poly(const Poly& the_pol){ size=the_pol.size; arr=new double[size]; for(unsigned int i=0;i>(std::istream& input,Poly& the_pol){ double value; char choice; do{ std::cout<<"Enter coef for "<>value; the_pol.arr[the_pol.size]=value; the_pol.size++; std::cout<<"Another(y/n)?: "; input>>choice; if(choice!='y') break; }while(true); return input; } std::ostream& operator<<(std::ostream& output,Poly& the_pol){ output<<"P(X)="; for(unsigned int i=0;i=0)?output<<"+"<p2.size)?p1.size:p2.size; Poly solution(longest); for(unsigned int i=0;ip1.size-1)?0.0:p1.arr[i]; double temp2 = (i>p2.size-1)?0.0:p2.arr[i]; solution.arr[i]=temp1+temp2; std::cout<<"Sol "<>p1; std::cout<>p2; std::cout<>hold; return 0; } ``````

 ``12345678910`` ``````Poly Poly::operator=(const Poly& the_poly){ Poly sol; sol.size=the_poly.size; for(unsigned int i=0;i

But it's not making any difference.

Try
 ``1234567`` ``````Poly& Poly::operator=(const Poly& the_poly){ size=the_poly.size; for(unsigned int i=0;i
Hi abhishekm,

You are absolutely right, although I am not sure why mine was not working except of course it was not returning a reference.

I remember reading that returning *this pointer is useful for chaining for example...

a=b=c=d=10;

Thanks again,

Mike
The difference between assignment operator overloading and other operators overloading is that you have declared = operator overload as a member function, whereas all others are friend functions.

Hence you need to modify the properties of the current object in consideration referenced by *this.

If you make this as a friend function also, then perhaps (I'm not sure) your way might work.

 ``12345678`` ``````Poly operator=(const Poly& the_poly){ Poly sol; sol.size=the_poly.size; for(unsigned int i=0;i

Topic archived. No new replies allowed.