Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          copying-objects/vers2/point-lineseg.cc - The corresponding cc file with implementations of the copy constructor and the assignment operator.Lecture 4 - slide 20 : 40
Program 2

#include <cmath>
#include <cstddef>
#include <iostream>
#include "point-lineseg.h"

Point::Point(double x_coord, double y_coord): x(x_coord), y(y_coord){
}

Point::Point(): x(0.0), y(0.0){
}

double Point::getx () const{
  return x;
}

double Point::gety () const{
  return y;
}

void Point::move(double dx, double dy){
  x += dx; y += dy;
}

double Point::distance_to(Point p) const{
  return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}

LineSegment::LineSegment(size_t s) : number_of_points{s}, points{new Point[s]} {
  std::cout << "LineSegment Constructor" << std::endl;
}

LineSegment::LineSegment(const LineSegment& ls){                // Copy constructor
  points = new Point[number_of_points = ls.number_of_points];
  for(int i = 0; i < number_of_points; i++) points[i] = ls.points[i];
  std::cout << "LineSegment copy constructor" << std::endl;
}  

LineSegment::~LineSegment(){                                    // Destructor
  delete[]points;
  std::cout << "LineSegment Destructor" << std::endl;
}  


LineSegment& LineSegment::operator= (const LineSegment& ls){    // Copy assignment operator
  if (this != &ls){  // not self-assignment;
    delete[]points;
    points = new Point[number_of_points = ls.number_of_points];
    for(int i = 0; i < number_of_points; i++) points[i] = ls.points[i];
  }
  std::cout << "LineSegment assignment" << std::endl;
  return *this;
}   


std::ostream& operator<<(std::ostream& s, const Point& p){
  return s << "(" << p.getx() << "," << p.gety() << ")" ;
}