Skip navigation

C++ pointer to a member function simple example

Original understanding from this


#include <stdlib.h>
#include <iostream>
using namespace std ;

class Obj
{
public:
  double fcn( int p1, int p2 )
  {
    return p1+p2;
  }
};

typedef double (Obj::*  /*AS*/FcnPtrType/*(end of name)*/  )( int, int ) ;

int main()
{
  // Create a pointer to A MEMBER FUNCTION OF THE "Obj" class, THAT RETURNS DOUBLE;
  // WHOSE INSTANCE NAME IS fcnPtr;
  // WHO ACCEPTS 2 ARGUMENTS, BOTH OF TYPE INT
  double (Obj::*  fcnPtr  )( int, int ) = &Obj::fcn ;

  // Let me break that down for you in steps:
  //double (Obj::*  // Create a pointer to A MEMBER FUNCTION OF "Obj" class, THAT RETURNS DOUBLE;
  //fcnPtr  )       // WHOSE INSTANCE NAME IS fcnPtr;
  //( int, int ) ;  // WHO ACCEPTS 2 ARGUMENTS, BOTH OF TYPE INT

  // Function pointer naming syntax is tricky to get the hang of,
  // but the tricky part is the NAME of the function pointer instance
  // is IN BRACKETS, BEFORE the parameter type listing.  This is
  // counter to what you'd normally expect in C++, where the
  // instance name always appears LAST in the line (breaks the
  // principle of least surprise, I suppose).
	
  // Now lets create an object (whose member function we will call
  // via the function pointer)

  Obj obj ;

  printf( "%f\n", (obj.*fcnPtr)( 3, 7 ) ) ;

  return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: