Search code examples
c++oopconstantsoperator-overloading

C++ overloading + operator runs into Problem with Constants


I defined a Vec2 object that should represent a 2d-vector. I tried to overload the + operator to implement vectoraddition but I get following error in Line 40:

error: no match for 'operator+' (operand types are 'const Vec2' and 'const Vec2')

Here's my code:

#include <iostream>

using namespace std;

class Vec2 {
private:
    double X;
    double Y;
public:
    Vec2(double x, double y){
        X = x;
        Y = y;
    }

double getX() const {
    return X;
}

double getY() const {
    return Y;
}

Vec2 operator+(Vec2 v ){
    Vec2 res(v.getX()+X, v.getY()+Y);
    return res;
}
};

ostream& operator<<(ostream& s , const Vec2& my_vec)
{
s << " ( "<< my_vec.getX()<< " , "<< my_vec.getY() <<" ) " ;
return s ;
}

int main()
{
    Vec2 const a(3,4);      cout << a << endl;
    Vec2 const b(3,4);      cout << b << endl;

    Vec2 c(a+b);       cout << c << endl;

    return 0;
}

Interestingly when you remove the "const" keyword from a in line 37 everything works, but I don't wan't to fix the error by changing the content of the main function. I am new to operator overloading, so thanks for the help.


Solution

  • The left operand, a, is const but your operator+ is not const qualified.

    You simply need to make it so. Also, instead of taking the right operand, b, by value, you can (optionally) take it by const reference:

    Vec2 operator+(const Vec2& v) const {
    //                            ^^^^^
    

    Demo


    An alternative is to only define operator+= as a member function and then to make operator+ a free function:

    class Vec2 {
    public:
    //...
        Vec2& operator+=(const Vec2& v) { // this changes *this, so not const qual.
            X += v.X;
            Y += v.Y;
            return *this;
        }
    };
    
    Vec2 operator+(const Vec2& lhs, const Vec2& rhs) {
        Vec2 result(lhs);
        result += rhs;     // uses the member function operator+=
        return result;
    }
    

    Demo


    Alternatively:

    Vec2 operator+(Vec2 lhs, const Vec2& rhs) {
        return lhs += rhs; // uses the member function operator+=
    }