Function Pointer Help Needed

N

neilsolent

I never did get my head round these :-(
After simplifying down for posting - I have a class CTest which is
supposed to have a static member variable called m_func, which points
to one of the two static member functions FuncA and FuncB. It is
initially set to NULL:


test.h
--------
class CTest
{
public:
static int (CTest::*m_func)(void);
static int FuncA();
static int FuncB();
};


test.c
--------
int (CTest::*m_func)(void) = NULL;

int CTest::FuncA()
{
return 1;
}

int CTest::FuncB()
{
return 2;
}

I don't think this code is right.
If I try to assign to m_func:

m_func = CTest::FuncA;

... I get compiler error: cannot convert `int ()()' to `int (CTest::*)
()' in assignment

If I try to run the function that m_func points to:

if (CTest::m_func != NULL)
{
int rc = (*CTest::m_func)();
}

... I get compiler error: invalid use of `unary *' on pointer to
member.

Can anyone help with my C++ grammar ?
 
N

nutrina9

I suggest to use a typedef to make the code clearer. The code below
worked in VS8.

#include <stdio.h>
#include <iostream>

typedef int (*func_ptr)(void);

class CTest
{
public:
static func_ptr m_func;

static int FuncA(void);
static int FuncB(void);

};

func_ptr CTest::m_func = NULL;

int CTest::FuncA()
{
return 1;
}

int CTest::FuncB()
{
return 2;
}

int main()
{
CTest::m_func = &CTest::FuncB;

if (CTest::m_func != NULL)
{
int rc = (*CTest::m_func)();
std::cout << "Result: " << rc << std::endl;
}

return 0;
}
 
A

Annie

neilsolent said:
static int (CTest::*m_func)(void);

Here, you are declaring a pointer to a normal member function,
and not to a static member function. Replace the line by:

static int (*m_func)(void);
 
N

neilsolent

Here, you are declaring a pointer to a normal member function,
and not to a static member function.  Replace the line by:

   static int (*m_func)(void);

Thanks Annie - much appreciated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top