Function pointer in C ++
I am trying to use a function pointer and I am getting this error:
cannot convert from void (__thiscall MyClass::*)(void)
tovoid (__cdecl *)(void)
// Header file - MyClass.h
class MyClass
{
public:
MyClass();
void funcTest();
protected:
void (*x)();
};
// Source file
#include "stdafx.h"
#include "MyClass.h"
MyClass::MyClass()
{
x = funcTest;
}
void MyClass::funcTest()
{
}
(Usage: Visual Studio 6)
Can anyone spot something that I missed?
source to share
You are trying to assign a member function pointer to a stand-alone function pointer. You cannot use these two elements interchangeably, because member functions always implicitly have a pointer this
as their first parameter.
void (*x)();
declares a pointer to a stand-alone function, but funcTest()
is a member function MyClass
.
You need to declare a pointer to a member function like this:
void (MyClass::*x)();
See the C ++ FAQ for details .
source to share
You are declaring a pointer to a function that takes no arguments and returns void. But you are trying to assign a member function pointer to it. You will need to declare a pointer to a member function pointer and accept its address like this: The &MyClass::funcTest
type of this pointer void (MyClass::*)()
Look at the function pointers tutorials
source to share
Yes, your type definition for x
is wrong. You have to define it as a member function pointer as suggested by the compiler, i.e. void(MyClass::*x)()
...
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
source to share