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?

+3


source to share


5 answers


because the member function is different from the normal one and hence the function pointers are different. Hence, you need to tell the compiler that you want the MyClass function pointer, and not the normal .youneed function pointer, to declare x as:void (MyClass::*x)();



+4


source


The type of a non-static member function is not void (*)()

. This void (MyClass::*)()

, which means you need to declare x

as:



void (MyClass::*x)();

x = &MyClass::funcTest; //use fully qualified name, must use & also

      

+5


source


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 .

+4


source


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

+1


source


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

+1


source







All Articles