Home >Backend Development >C++ >Why Doesn't `bigCat.*pcat()` Work When Calling Member Functions Through Pointers?
Calling Functions Through Member Function Pointers
When utilizing member function pointers, it's crucial to ensure their correct invocation. Consider the sample code:
class cat { public: void walk() { printf("cat is walking \n"); } }; int main(){ cat bigCat; void (cat::*pcat)(); pcat = &cat::walk; bigCat.*pcat(); }
However, an error occurs when attempting to call the function using bigCat.*pcat();. This is because additional parentheses are necessary in the function call syntax.
Correct Syntax for Calling Member Function Pointers
To invoke member functions correctly through member function pointers, the parentheses operator precedence must be observed. The correct syntax for the function call is:
(bigCat.*pcat)();
This ensures that the function call operator (()) has higher precedence than the pointer-to-member binding operator (.*). Unary operators generally have precedence over binary operators. Therefore, the parentheses are necessary to explicitly specify that the member function walk() is being called on the object bigCat.
With the corrected syntax, the code will successfully execute and print "cat is walking n" to the console.
The above is the detailed content of Why Doesn't `bigCat.*pcat()` Work When Calling Member Functions Through Pointers?. For more information, please follow other related articles on the PHP Chinese website!