Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Move constructors and copy constructors


Here is a version with comments and explanations:

#include <cmath>
#include <iostream>

using namespace std;

class Point {
private: 
  double x, y;

public:
  Point();                    // default constructor:  (0,7)
  Point(double x);            // (x, 20)
  Point(double x, double y);  // (y, y)  
  Point(const Point& p);      // copy constructor: (p.x+1, p.y+2) 
  Point(Point&& p);           // move constructor: (p.x-3, p.y-4) 

  double getx () const;
  double gety () const;
};

std::ostream& operator<<(std::ostream&, const Point&);

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

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

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

Point::Point(const Point& p): x(p.x + 1.0), y(p.y + 2.0){
}

Point::Point(Point&& p): x(p.x - 3.0), y(p.y - 4.0){
}


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

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

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


const Point& pf(const Point& p){
  cout << "Inside pf: Parameter: " << p << endl;
  return p;
}

int f(){
  Point p;
  cout << "Point p: " << p << endl;   // (0,7)

  cout << "pf(q): " << pf(p) << endl; // (0,7)
                                      // Passing p via const L-value reference (0,7)  - no copy constructor nor rvalue constructor.
                                      // Returning a const reference: (0,7)

  Point q = pf(p);                    // Passing p via const L-value reference (0,7)  - no copy constructor nor rvalue constructor.
                                      // Returning an L-value reference (0,7). Then copying it to q via copy constructor (!!). 
  cout << "Point q: " << q << endl;   // (1,9) 

  Point r = pf(Point{10,12});         // Passing Point{10,12} as above  - no copy constructor nor rvalue constructor.
                                      // Returning an L-value reference (10,12). Copying it to r via copy constructor.
  cout << "Point r: " << r << endl;   // (11,14)

}

int main(){
  f();
}