C++ old struct operator overloading syntax changed?

Viewed 64

I am building my old CPP codes from 20+ years ago, but g++ gives build error. Can someone explains me what has changed? Thanks. (It was fine in turbo C)

error:

t_overload.cpp:8:40: error: no matching constructor for initialization of 'Point'
    Point operator+(Point& v) { return Point(x+v.x, y+v.y); }
                                       ^~~~~~~~~~~~~~~~~~~

cpp file:

#include <stdio.h>

struct Point {
    int x, y;
//    Point(Point& v) {set(v.x, v.y);}     // build okay without this line; error if uncomment
    Point(int a, int b) {set(a,b);}
    void set(int a, int b) {x=a, y=b;}
    Point operator+(Point& v) { return Point(x+v.x, y+v.y); }
};

int main() {
    Point a(1,2);
    Point b(a);

    Point c = a + b;
    printf("%d %d\n", c.x, c.y);
}
1 Answers
Point(Point& v)

Copy constructors should take constant parameters, this should be:

Point(const Point& v)

But given what that copy constructor does, it's completely unnecessary. You can get rid of it, completely.

Point operator+(Point& v) 

Similarly, the parameter to the overload should be constant:

Point operator+(const Point& v) 

See "What are the basic rules and idioms for operator overloading?"

Both of these issues, together with rather nuanced and delicate rules of overloading and how temporaries bind to function parameters, were resulting in your compilation errors.

Related