Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Pointer to a member function

  1. Dec 15, 2009 #1


    User Avatar
    Science Advisor

    I'm even sure I'm using the correct terminology, but I'm hoping someone can help me with a common problem I encounter.

    I frequently use the Gnu Science Libraries (GSL) in my C++ code to do various numerical grunt work. Commonly I need to provide a pointer to a function for a GSL routine to work (e.g. pointer to a function that GSL will find the minimum of for instance). Now, often the function I'm interested in is a member function of some object. But I can't provide a pointer to that, since the pointer to a member function is not the same as a pointer to a function.

    Instead, I restort to making small wrapper functions that take a void pointer as the input, and send the relevant object to the class using the 'this' keyword. This way the function can access the members of that object (I make this function a friend of the relevant class).

    These little wrapper functions are annoying though, since because they are free standing I have to make sure I use unique names, which can be annoying when re-using code and for big projeccts.

    What I'd like to know is whether there is a better way to do this, for instance can you somehow cast the pointer to the member function to be a pointer to a function and just send that to the GSL routines? Sorry if this doesn't make much sense, I 'learned' C++ in a very ad hoc way, so I get the terminology mixed up sometimes.
  2. jcsd
  3. Dec 15, 2009 #2
    Even if you were to cast the pointer to the member into the pointer to a normal function successfully (using reinterpret_cast or some such contraption), things wouldn't work well, because class member functions and normal functions have different calling conventions, and GSL wouldn't know to pass "this" pointer to your function.

    You can pass a pointer to a static class member, that's almost the same as making a wrapper, but a bit neater.
  4. Dec 15, 2009 #3


    User Avatar
    Science Advisor

    Thanks, perfect solution!
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Threads - Pointer member function Date
C/++/# Usefulness of Pointers in C++? Mar 9, 2017
C/++/# Dynamic Arrays (One, two, three dimensions) Jul 12, 2016
Pointers to const in func parameters Sep 13, 2015
Question on pointers (ROOT TTree example) Jul 29, 2015
[C++] Pointers to member functions May 18, 2008