Search code examples
c++sumintoperator-overloadingoperator-keyword

C++ overloading of the plus operator


I want to add 2 objects, by overloading the + operator, but my compiler says there's no matching function to call to point::point(int, int). Can somebody please help me with this code, and explain the error ? thank you

#include <iostream>

using namespace std;

class point{
int x,y;
public:
  point operator+ (point & first, point & second)
    {
        return point (first.x + second.x,first.y + second.y);
    }
};

int main()
{
    point lf (1,3)
    point ls (4,5)
    point el = lf + ls;
    return 0;
}

Solution

  • You can just change your code like this,

    #include <iostream>
    
    using namespace std;
    
    class point {
        int x, y;
    public:
        point(int i, int j)
        {
            x = i;
            y = j;
        }
    
        point operator+ (const point & first) const
        {
            return point(x + first.x, y + first.y);
        }
    
    };
    
    int main()
    {
        point lf(1, 3);
        point ls(4, 5);
        point el = lf + ls;
    
        return 0;
    }
    

    Hope this helps...