2

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);
}
oiman
  • 23
  • 4
  • This question is closed for the reason of duplicating another one: "copy constructor must use const object". Actually the error here complained within the operator overloading. Instead of jumping to the conclusion saying they are the same problem, a better elaborating why they are the same is more helpful, as in Sam's answer. Thanks. – oiman Dec 06 '20 at 17:38
  • I voted to close as a duplicate because the [accepted answer's](https://stackoverflow.com/a/16956812/10957435) third point is exactly what you're running into. Sorry if I left you confused. Confusion was certainly not my intention. –  Dec 06 '20 at 23:35

1 Answers1

0
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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Thanks for explanation. Changing the copy constructor argument to const fixed the error. (The question is locked. I can't upvote..) – oiman Dec 06 '20 at 17:22