How to return void function pointer

Mar 22, 2008 at 8:12am
Hello all
im trying to build function that will return void function pointer
what is mean is ( not working )
the main function
void * myClass::getFunction(int type){
if(type==1)
return &myClass::Test1;
if(type==2)
return &myClass::Test2;
}

void myClass::Test1(){
printf("nada1");
}

void myClass::Test2(){
printf("nada2");
}


what im doing wrong here ?
Mar 22, 2008 at 11:15am
This is how to use a function pointer, but it only works with global functions (not member functions in myClass). I have added some code, so that it's possible to compile and run this as a program. (Note that I had to add return 0 if no function was found, and I added a newline after the output from Test1 and Test2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cstdio>
using std::printf;

// Define the type func as a pointer to a void function with no parameters
typedef void (*func)();


void Test1() {
    printf("nada1\n");
}

void Test2() {
    printf("nada2\n");
}

func getFunction(int type) {
    if(type==1)
        return &Test1;
    if(type==2)
        return &Test2;
    else
        return 0;
}

int main() {
    func p = 0;
    
    p = getFunction(1);
    (*p)();
    
    p = getFunction(2);
    (*p)();
}


If you want a pointer to a member function in a class, the syntax is a little different:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <cstdio>
using std::printf;

class myClass {
public:
    // Define the type func as a pointer to a void member function 
    // in this class with no parameters
    typedef void (myClass::*func)();
    
    func getFunction(int);
    void Test1();
    void Test2();
};

myClass::func myClass::getFunction(int type){
    if(type==1)
        return &myClass::Test1;
    if(type==2)
        return &myClass::Test2;
    else
        return 0;
}

void myClass::Test1(){
    printf("nada1\n");
}

void myClass::Test2(){
    printf("nada2\n");
}

int main() {
    myClass c;
    myClass::func p;
    
    p = c.getFunction(1);
    (c.*p)();
    
    p = c.getFunction(2);
    (c.*p)();
    
    // Or using a pointer:
    myClass *cp = &c;
    
    p = cp->getFunction(1);
    (cp->*p)();
    
    p = cp->getFunction(2);
    (cp->*p)();
}
Last edited on Mar 22, 2008 at 11:17am
Topic archived. No new replies allowed.