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

Exercise solution:
Contrasting use of C# and C++ classes: Class Point


Here follows a number of programs that illustrate the issues, which are brought up in this exercise.

1. The C++ client program with pointers - free store allocation

#include <iostream>
#include "point.h"

using namespace std;

Point *pointmover(Point *pa, Point *pb){
  pa->move(5,6);
  pb->move(-5,-6);
  return pb;
}

void go(){
  Point *p1 = new Point(1, 2),
        *p2 = new Point(3, 4),
        *p3 = p1,
        *p4 = p2,
        *p5;

    p5 = pointmover(p1, p2);

    cout << *p1 << endl <<    // (6,8)
            *p2 << endl <<    // (-2,-2)
            *p3 << endl <<    // (6,8)
            *p4 << endl <<    // (-2,-2)
            *p5 << endl;      // (-2,-2)

  delete p1;
  delete p2;
}

int main(){
  go();
}


 

2. The C++ client program with pointers - stack allocation. Notice that the free store is not used, and therefore there is no need for calling delete.

#include <iostream>
#include "point.h"

using namespace std;

Point *pointmover(Point *pa, Point *pb){
  pa->move(5,6);
  pb->move(-5,-6);
  return pb;
}

void go(){
  Point p(1,2),
        q(3,4),
        *p1 = &p,
        *p2 = &q,
        *p3 = p1,
        *p4 = p2,
        *p5;

    p5 = pointmover(p1, p2);

    cout << *p1 << endl <<    // (6,8)
            *p2 << endl <<    // (-2,-2)
            *p3 << endl <<    // (6,8)
            *p4 << endl <<    // (-2,-2)
            *p5 << endl;      // (-2,-2)

  // Nothing to deallocate with delete!
}

int main(){
  go();
}


 

3. The C++ client program with references

#include <iostream>
#include "point.h"

using namespace std;

Point &pointmover(Point &pa, Point &pb){
  pa.move(5,6);
  pb.move(-5,-6);
  return pb;
}

void go(){
  Point p1(1, 2),
        p2(3, 4),
        &p3 = p1,
        &p4 = p2;

  Point &p5 = pointmover(p1, p2);

  cout << p1 << endl <<   // (6,8)
          p2 << endl <<   // (-2,-2)
          p3 << endl <<   // (6,8)
          p4 << endl <<   // (-2,-2)
          p5 << endl;     // (-2,-2)
}

int main(){
  go();
}


 

4. The C++ client program with Point value semantics

// Notice: New sematics due to use of call-by-value.

#include <iostream>
#include "point.h"

using namespace std;

Point pointmover(Point pa, Point pb){
  pa.move(5,6);
  pb.move(-5,-6);
  return pb;
}

void go(){
  Point p1(1, 2),
        p2(3, 4),
        p3 = p1,    // Copy p1
        p4 = p2;    // Copy p2

  Point p5 = pointmover(p1, p2);   // Pass copies. 

  cout << p1 << endl <<   // (1,2)
          p2 << endl <<   // (3,4)
          p3 << endl <<   // (1,2)
          p4 << endl <<   // (3,4)
          p5 << endl;     // (-2,-2), a moved copy of p2, copied back from pointmover.
}

int main(){
  go();
}