Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'                pointer-to-member/prog.cc - A program that illustrates pointer to Point member functions.Lecture 5 - slide 14 : 40
Program 3

// Ilustration of pointers to members.

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

// Typedef the Point move signature:
typedef void (Point::* Ptr_to_move)(double, double);  // Ptr_to_move becomes the name of the function signature:
                                                      // (double, double) -> void
                                                      // Special declarator syntax:   Class::*   pointer to member in Class.
void f(int selector, Point *p, Point q){
  Ptr_to_move mv;                                     // A variable which can be assigned to a pointer to a member
                                                      // to a Point move function.
  // Assign the member pointer mv:
  switch(selector){
    case 1: {mv = &Point::move_relative; break;}      // mv becomes a member pointer to move_relative.
    case 2: {mv = &Point::move_absolute; break;}      // mv becomes a member pointer to move_absolute.
    case 3: {mv = &Point::move_funny; break;}         // mv becomes a member pointer to move_funny.
  }

  (p->*mv)(1,1);                                      // Call the move function refered from mv on Point pointer p.
  (q.*mv)(2,2);                                       // Call the move function on q.

  std::cout << "In f, p: " << *p << std::endl;        // (2,3)
  std::cout << "In f, q: " << q <<  std::endl;        // (5,6)
}

int main(){
  using namespace std;

  Point p1(1,2),
        p2(3,4);

  f(1, &p1, p2);                                      // p1 is moved relatively, because 1 is passed as selector to f.
  cout << "In main, p1: " << p1 << endl;              // (2,3)  
  cout << "In main, p2: " << p2 << endl;              // (3,4)  - p2 not affected, of course, because it is passed by value.
}