-1

I've been writing a polynomial class and I was overloading operators for it. I managed to (I think) successfully overload the += operator and now I created an external function that uses += for addition just like advised in many sources. It works but I can't chain them for some reason When I try to add polynomials like this

poly a, b, c, d;
a=b+c+d;

I get an error: no matching function for call to 'poly::poly(const poly)'

My += function's main body isn't all that important but that's what it's like:

poly& operator+= (const poly& a){
        //implemented +=
        return *this;

    }

My addition function (outside of the class) looks like this:

const poly operator+ (poly a, const poly & b){
    a+= b;
    return a;
}

What am I doing wrong here?

  • why is `operator+` returning a `const`? – kmdreko Nov 03 '17 at 21:51
  • 2
    Both `a` and `b` should be `const &`. – Dúthomhas Nov 03 '17 at 21:52
  • 2
    You are missing a [copy constructor](https://stackoverflow.com/questions/2168201/what-is-a-copy-constructor-in-c). – Robᵩ Nov 03 '17 at 21:53
  • 1
    Looks like you don't have a copy constructor for `poly`. `b + c` produces a `const poly` and your `operator +` takes a `poly` as first argument so it has to copy the `const poly` into the `poly a` but it can't, because there is no copy constructor `poly::poly(const poly &)`. – nwp Nov 03 '17 at 21:54

1 Answers1

1

Your poly class is missing a copy constructor of the form poly(const poly&). Note that if you already have a poly(poly&) that isn't enough. You need a copy constructor that takes a const poly& as a parameter.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308