function pointers

Aug 12, 2010 at 3:27pm

I'm trying to pass a function pointer into the constructor of a class, and I want to have a getter that will return that function so I can be called as an instance of that class. Does that sound possible? Here is what I have right now.


1
2
3
4
5
6
7
8
9
10
11
12
class Input{
public:
   Input(const void *v_function):validation_function_(v_function){}

   const void* validation_function()const
   {
       return validation_function_;
   }

private:
   void (*validation_function_)();
};


Then inside a GUI class which contains a number of Input objects - I want to be able to call something like this.


1
2
3
4
Input myinput(validate_printer);

myinput.validate_function();


I want that to call a function in the GUI class called void validate_printer().

Does this sound possible. I think I just have the pointers and the voids messed up in the Input constructor, but I'm not sure.
Aug 12, 2010 at 3:52pm
You're doing it almost perfectly, but what I don't understand is why are you passing the function pointer through a generic pointer? You seem to understand the function pointer syntax, so that doesn't really make sense.
FYI, casting between function pointers and data pointers is unsafe.
Aug 12, 2010 at 5:45pm
This is all possible, but note that the syntax you have above will only bind the 'validation_function_' pointer to a non-member or static member function. The syntax (and pointer structure) is different for member function pointers, so the above will only work if 'validate_printer' is either static or not a member of any class. Also, you could change the syntax such that validation_function_ is specifically defined to be a member function pointer of some class (for example, "void (GUIClass::*validation_function_)();"), but then only member functions of GUIClass could be called using this function pointer, and you would need a pointer to a GUIClass object to actually call validation_function_.

Post more code with a simple example of what you are trying to do, and someone will likely be able to offer suggestions on how to make it work.

--Rollie
Aug 12, 2010 at 8:04pm
I think all that's wrong here is the syntax on the getter in my Input class, but I don't know what it should be?
Aug 12, 2010 at 8:55pm
Aug 12, 2010 at 10:08pm
I think your syntax is a bit squiffy. I think it should probably be more like this:
1
2
3
4
5
6
7
8
9
10
11
12
class Input{
public:
   Input(void (*v_function)()):validation_function_(v_function){}

   void (* validation_function())() const
   {
       return validation_function_;
   }

private:
   void (*validation_function_)();
};
Aug 13, 2010 at 7:38am
1
2
3
4
   void(*)()validation_function()
   {
       return validation_function_;
   }


next time just use typedef to make things easier =p
Last edited on Aug 13, 2010 at 7:40am
Topic archived. No new replies allowed.