pointer to function

Jul 9, 2008 at 12:33pm
Hi
I have a program with pointer to a function. It dosn't work for me but I cant find the problem. Please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void (*fp)();

class a{
public:
	void func(){/*do sth*/}
};

void dosth (void (*ab)(void)){
	(*ab)();
}

int main (){
	dosth(a::func);
	return 0;
}
Jul 9, 2008 at 1:22pm
Member functions have a this pointer as the first argument. In your example, func() will have the address of the class a object used to call the function. This argument is supplied by the compiler.

Therefore, you can't use member functions without an object.

Therefore, you can't take the address of a member function by itself.

Therefore, you can't use a member function with a function pointer.
Jul 9, 2008 at 2:00pm
You can do it, though, if you are willing to use the <functional> library, with the mem_fun() adaptors:
http://msdn.microsoft.com/en-us/library/wtc0dy7y(VS.71).aspx

Boost also has improved function adaptors (that work better than the STL ones):
http://www.boost.org/doc/libs/1_35_0/libs/functional/index.html

Good luck!
Jul 9, 2008 at 4:28pm
Although the solution proposed by Duoas is by far the most elegant solution, there is another way, as long as func in class a is declared as static.
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
#include <iostream>

using namespace std;

//void (*fp)();

extern "C"
 {
    /*
     * ptr to C function; strips off class this pointer data
     */
    typedef void (*cfunc_p)(void);
 }

 // ptr to C++ function;
 typedef void (*cppfunc_p)(void);

 inline cfunc_p setfuncPtr(cppfunc_p f)
 {
    return (cfunc_p)f;
 }
class a{
public:
	static void func(){cout << "Hello" << endl;}
};

void dosth (void (*ab)(void)){
	(*ab)();
}


int main(int argc, char** argv)
{
	dosth(setfuncPtr(a::func));
	return 0;
}

Jul 10, 2008 at 1:34am
You can try this,it doesn't use the extern!

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
/********************************************************************
	created:	2008/07/10
	created:	10:7:2008   10:48
	filename: 	f:\coding\C++\CodeGuru_FuncPointer\CodeGuru_FuncPointer\CodeGuru_FuncPointer.cpp
	file path:	f:\coding\C++\CodeGuru_FuncPointer\CodeGuru_FuncPointer
	file base:	CodeGuru_FuncPointer
	file ext:	cpp
	author:		hecan
	
	purpose:	===============VC7.0 + WinXP sp2 pass================
*********************************************************************/

#include <iostream>

using namespace std;

class CPointer
{
public:
	void func()
	{
		cout << "!!!" <<endl;
	}
	void ( *pf)();
};

int main (){
	CPointer aa;
	void (CPointer:: *pf)() = &(CPointer::func);
	(aa.*pf)();
	return 0;
}
Topic archived. No new replies allowed.