Connecting Tech Pros Worldwide Forums | Help | Site Map

How can I use a function pointer to non-static member function of a class.

Assertor
Guest
 
Posts: n/a
#1: Mar 9 '06
Hi All,

Except function pointer to a static member funciton of a class (or a
function).

As the following code, I could pointer a non-static member function of
a class.
And "Equal" was printed, the pointer has meaning.

But how can I use it??
I.e., I'd like to call the member method by using the function pointer
(like using c function pointer).


class TMyClass
{
public:
int DoIt(float a, char b, char c){ ... };
}

int (TMyClass::*pt2Member)(float, char, char) = NULL;
pt2Member = &TMyClass::DoIt;

// C++
if(pt2Member== &TMyClass::DoIt)
cout << "Equal" << endl;

pt2Member(1.2f, 'a', 'b'); //<------ error.

As u know, in case that the function pointer piont a non-static member
function, the pointer can invoke the member function.


Victor Bazarov
Guest
 
Posts: n/a
#2: Mar 9 '06

re: How can I use a function pointer to non-static member function of a class.


Assertor wrote:[color=blue]
> [..]
> As the following code, I could pointer a non-static member function of
> a class.
> And "Equal" was printed, the pointer has meaning.
>
> But how can I use it??[/color]

You need an instance of the class in the form of an object, a reference,
or a pointer.
[color=blue]
> I.e., I'd like to call the member method by using the function pointer
> (like using c function pointer).
>
>
> class TMyClass
> {
> public:
> int DoIt(float a, char b, char c){ ... };
> }[/color]
;
[color=blue]
>
> int (TMyClass::*pt2Member)(float, char, char) = NULL;
> pt2Member = &TMyClass::DoIt;[/color]

I suppose this is inside a function of some kind.
[color=blue]
>
> // C++
> if(pt2Member== &TMyClass::DoIt)
> cout << "Equal" << endl;
>
> pt2Member(1.2f, 'a', 'b'); //<------ error.[/color]

You need an instance of 'TMyClass', and then use it:

TMyClass t;

(t.*pt2Member)(1.2f, 'a', 'b');
[color=blue]
> As u know, in case that the function pointer piont a non-static member
> function, the pointer can invoke the member function.[/color]

Huh?

V
--
Please remove capital As from my address when replying by mail
Closed Thread