Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call through a member function pointer?

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(); } 
like image 240
Nayana Adassuriya Avatar asked Aug 30 '12 02:08

Nayana Adassuriya


People also ask

Can we call member function using this pointer?

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.

How do you access member functions using pointers?

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.

How do you call a function with a function pointer?

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

How do you call a member function?

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.


1 Answers

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.

like image 165
James McNellis Avatar answered Sep 27 '22 22:09

James McNellis