Exercises in this lecture  previous -- Keyboard shortcut: 'p'        Go to the slide, where this exercise belongs -- Keyboard shortcut: 'u'  

Exercise 4.2
Move constructors and copy constructors


Take a look at this variant of class Point from above - all parts in one file. Notice the difference between the parameters of the function pf above, and pf in the following version of the program.

#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;   

  Point q = pf(p);                    
                                      
  cout << "Point q: " << q << endl;   

  Point r = pf(Point{10,12});         
                                      
  cout << "Point r: " << r << endl;   

}

int main(){
  f();
}

Predict the results of the program. More specifically, which constructors are used in f?

Do you find it easy and natural to decide which kind of constructors are used for parameter passing and value return?


Solution