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

A

Assertor

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.
 
V

Victor Bazarov

Assertor said:
[..]
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??

You need an instance of the class in the form of an object, a reference,
or a pointer.
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;

I suppose this is inside a function of some kind.
// C++
if(pt2Member== &TMyClass::DoIt)
cout << "Equal" << endl;

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

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

TMyClass t;

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

Huh?

V
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top