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?
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 .
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.
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);
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).
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.
int (*x)()
is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With