// CSE 303, Spring 2009, Marty Stepp // Implements a LineSegment class so that we can talk about destructors, // copy constructors, overloading the = operator, and other icky C++ features. #include "Point.h" #include "LineSegment.h" // helper initialization function called in several places void LineSegment::init(int x1, int y1, int x2, int y2) { p1 = new Point(x1, y1); p2 = new Point(x2, y2); } // normal constructor LineSegment::LineSegment(int x1, int y1, int x2, int y2) { p1 = new Point(x1, y1); p2 = new Point(x2, y2); } // "copy constructor" called when one LineSegment is declared equal to another; // makes a deep copy of the p1/p2 points inside this line segment. LineSegment::LineSegment(const LineSegment& line) { p1 = new Point(line.getX1(), line.getY1()); p2 = new Point(line.getX2(), line.getY2()); } // destructor; called when a LineSegment object is deleted or goes out of scope. // We need to write this to avoid leaking memory when a point LineSegment::~LineSegment() { delete p1; delete p2; } // This overloaded assignment = operator makes sure to free my p1/p2 objects // before replacing them with the values from the given other object. // This is done to avoid a memory leak of my old p1/p2 objects. const LineSegment& LineSegment::operator=(const LineSegment& rhs) { if (this != &rhs) { delete p1; delete p2; init(rhs.getX1(), rhs.getY1(), rhs.getX2(), rhs.getY2()); } return *this; // always return *this from = } int LineSegment::getX1() { return p1->getX(); } int LineSegment::getY1() { return p1->getY(); } int LineSegment::getX2() { return p2->getX(); } int LineSegment::getY2() { return p2->getY(); } double LineSegment::length() { return p1->distance(*p2); } double LineSegment::slope() { int dy = p2->getY() - p1->getY(); int dx = p2->getX() - p1->getX(); return (double) dy / dx; } void LineSegment::translate(int dx, int dy) { p1->translate(dx, dy); p2->translate(dx, dy); }