I'm trying to do some testing with member function pointer. What is wrong with this code? The bigCat.*pcat();
statement doesn't compile.
class cat { public: void walk() { printf("cat is walking \n"); } }; int main(){ cat bigCat; void (cat::*pcat)(); pcat = &cat::walk; bigCat.*pcat(); }
You can use pointers to member functions in the same manner as pointers to functions. You can compare pointers to member functions, assign values to them, and use them to call member functions.
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
Calling a Function Through a Function Pointer in C using function pointer (a) int area = (*pointer)(length); // 3. using function pointer (b) int area = pointer(length);
The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator.
More parentheses are required:
(bigCat.*pcat)(); ^ ^
The function call (()
) has higher precedence than the pointer-to-member binding operator (.*
). The unary operators have higher precedence than the binary operators.
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