By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,925 Members | 1,129 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,925 IT Pros & Developers. It's quick & easy.

How can I call class member function by a globle function pointer?

P: n/a
Dear all,
I'm puzzled about the usage of class member function. Any help would be

appreciated.
class Account {
...
public:
void test(int i) {};
...

};
// error: must use .* or ->* to call pointer-to-member function
void (*funcPtr)(int i) = &Account::test;

How can I call class member function by a globle function pointer?

Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
"zx***********@gmail.com" wrote:

Dear all,

I'm puzzled about the usage of class member function. Any help would be

appreciated.

class Account {
...
public:
void test(int i) {};
...

};

// error: must use .* or ->* to call pointer-to-member function
void (*funcPtr)(int i) = &Account::test;

How can I call class member function by a globle function pointer?


You need an object for which you want to call a member function!
eg.

#include <iostream>

class Account {
public:
void test(int i) { std::cout << i << std::endl; }
};

void (Account::*funcPtr)(int i) = &Account::test;
Account* pTheAccount;

void foo()
{
Account Test;
(Test.*funcPtr)( 7 );
(pTheAccount->*funcPtr)( 5 );
}

int main()
{
Account MyAccount;
pTheAccount = &MyAccount;

foo();
}

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #2

P: n/a
Thanks
But is there any way to call a member function by a outer-class
function pointer?

Jul 23 '05 #3

P: n/a
> But is there any way to call a member function by a outer-class
function pointer?


No. The type of f() in

class C
{
void f();
};

is not void(), but void C::(). Hence, to get a pointer to it, you must
do

void (C::*p)();

Now if you want to use a pointer to a free function with a class
member, you must make it static. For example :

class C
{
public:
static void start();
};

void f()
{
void (C::*p1)() = &C::start; // error
void (*p2)() = &C::start; // ok
}

You'll have to do that often if you want to use classes and C functions
together. For example, many win32 functions expect a pointer to a free
function, not to a class member and you'll have to use a static member.

Jonathan

Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.