Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling pointer-to-member function C++

I have a pointer to a member function defined within a class, e.g.:

class Example {
   void (Example::*foo)();

   void foo2();
};

In my main code, I then set foo as:

Example *a;
a->foo = &Example::foo2;

However, when I try to call foo:

a->foo();

I get the following compile time error: "error: expression preceding parentheses of apparent call must have (pointer-to-) function type". I'm assuming I'm getting the syntax wrong somewhere, can someone point it out to me?

like image 453
wolfPack88 Avatar asked May 15 '14 18:05

wolfPack88


People also ask

How do you call a pointer to a member function?

Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);

Can we call member function using this pointer in constructor?

the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.

Can a pointer be passed to a function?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

Will point to the object for which member function has been called?

1. Which is the pointer which denotes the object calling the member function? Explanation: The pointer which denotes the object calling the member function is known as this pointer. The this pointer is usually used when there are members in the function with same name as those of the class members.


1 Answers

to call it you would do: (a->*(a->foo))()

(a->*X)(...) - dereferences a member function pointer - the parens around a->*X are important for precedence.

X = a->foo - in your example.

See ideone here for working example

like image 156
Bob Fincheimer Avatar answered Oct 11 '22 23:10

Bob Fincheimer