user1287929
user1287929

Reputation: 33

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) to void (__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()
{

}

(Using: Visual Studio 6)

Can anyone notice anything that I've missed?

Upvotes: 3

Views: 312

Answers (5)

Péter Török
Péter Török

Reputation: 116306

You are trying to assign a member function pointer to a standalone function pointer. You can't use the two interchangeably, because member functions always implicitly have the this pointer as their first parameter.

void (*x)();

declares a pointer to a standalone function, while funcTest() is a member function of MyClass.

You need to declare a member function pointer like this:

void (MyClass::*x)();

For more details see the C++ FAQ.

Upvotes: 4

NullPoiиteя
NullPoiиteя

Reputation: 57332

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

Upvotes: 4

devil
devil

Reputation: 1839

Yes your type definition for x is wrong. You need to defined 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

Upvotes: 1

pmr
pmr

Reputation: 59841

You declare a pointer to a function not taking any arguments and returning void. But you try to assign a member function pointer to it. You will need to the declare a pointer to a member function pointer and take its address like this: &MyClass::funcTest The type of this pointer is void (MyClass::*)() Have a look at the function pointer tutorials

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361762

The type of non-static member-function is not void (*)(). It is void (MyClass::*)(), which means you need to declare x as:

void (MyClass::*x)();

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

Upvotes: 5

Related Questions