简体   繁体   中英

Is it possible to create a pointer to a non-static member-function in C++?

I was wondering if it's possible to create and use a pointer to a non-static member-function. When I compile my code without the pointer to the member-function being static, it gives a compilation error.

Thanks...

In short: Yes, it's possible, and no, it doesn't do what you think.

The crucial fact is that non-static member functions are not functions (just like a Douglas-fir is not a fir). They are member functions, and that's something different. They can only be invoked on a given object instance.

Thus in order to call the member function X::foo() of a given instance X a; , ie to perform the call a.foo() , you need both the information that you want to use X::foo() , and that you want to invoke it on the instance a . The former is provided by a pointer-to-member-function , which is not a pointer , and the latter is provided by an instance pointer or reference:

struct X { int foo(bool, char); };  // class definition

X a;          // an instance
X * p = &a;   // just for demonstration

int (X::*)(bool, char) ptmf = &X::foo;   // pointer-to-member-function

Now to invoke:

(a.*ptmf)(false, 'a');
(p->*ptmp)(true, 'z');

In a nutshell: foo alone does not let you call anything. The callable entity is the pair (&X::foo, a) , which lets you call a.foo() .

Yes, it is possible to create pointer to member functions in C++. See this FAQ: pointers-to-members

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM