Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer to member function

I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated.

In this example, I would like the output to be "1"

class A { public:  int f();  int (*x)(); }  int A::f() {  return 1; }   int main() {  A a;  a.x = a.f;  printf("%d\n",a.x()) } 

But this fails at compiling. Why?

like image 769
Mike Avatar asked Mar 08 '10 15:03

Mike


People also ask

How do you get a pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

Can we call member function using this pointer?

Function pointer to member function in C++ In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe.

How do you call a function from a pointer object?

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);

Which pointer is not passed to member function?

The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).


Video Answer


2 Answers

The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:

class A { public:  int f();  int (A::*x)(); // <- declare by saying what class it is a pointer to };  int A::f() {  return 1; }   int main() {  A a;  a.x = &A::f; // use the :: syntax  printf("%d\n",(a.*(a.x))()); // use together with an object of its class } 

a.x does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a. Prepending a another time as the left operand to the .* operator will tell the compiler on what object to call the function on.

like image 124
Johannes Schaub - litb Avatar answered Sep 21 '22 04:09

Johannes Schaub - litb


int (*x)() is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;.

like image 42
Bertrand Marron Avatar answered Sep 23 '22 04:09

Bertrand Marron