0

I'm getting the following output:

[1, 1] Segmentation fault

Any ideas what's causing the segmentation fault?

#include <iostream>
using namespace std;

// point class

class Point {
    friend std::ostream &operator<<( ostream &, const Point &);
    public:
        Point (int = 0, int = 0);
        int getX() const {return x;};
        int getY() const {return y;};
        void setX(int _x) {x = _x;};
        void setY(int _y) {y = _y;};
        Point &operator+(const Point& p) {
            Point p_self;
            p_self.setX(x + p.getX());
            p_self.setY(y + p.getY());
            // suspect this line is causing the segmentation fault
            return p_self;
        }
    protected:
        int x, y;
};

Point::Point (int a, int b) {x = a; y = b;}

std::ostream &operator<<(ostream &output, const Point &p) {
    output << '[' << p.x << ", " << p.y << ']';
    return output;
}

int main() {
  Point p = Point(1, 1);
  cout << p << endl;
  Point p2 = p + p;
  cout << p2 << endl;
  return 0;
}

I'm getting the following output:

[1, 1] Segmentation fault

Any ideas what's causing the segmentation fault?

stonebird
  • 329
  • 4
  • 9
  • 1
    `warning: reference to local variable 'p_self' returned` – paolo Aug 21 '22 at 16:22
  • 2
    Your `operator+` returns a dangling reference to a local. – wohlstad Aug 21 '22 at 16:23
  • 1
    I recommend [this operator overload canonical implementation reference](https://en.cppreference.com/w/cpp/language/operators#Canonical_implementations). Besides saying that `operator+` should be implemented in terms of `operator+=` it also says that `operator+` should return a "value" (an object) not a reference. – Some programmer dude Aug 21 '22 at 16:29
  • `operator+` should be returning a brand new `Point` object, not a reference to one. On the other hand, `operator +=` is where you would return a reference to the current point object, i.e. `return *this;` – PaulMcKenzie Aug 21 '22 at 16:45

0 Answers0