Home > Backend Development > C++ > Why Doesn't `bigCat.*pcat()` Work When Calling Member Functions Through Pointers?

Why Doesn't `bigCat.*pcat()` Work When Calling Member Functions Through Pointers?

Linda Hamilton
Release: 2024-12-15 16:42:15
Original
673 people have browsed it

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();
}
Copy after login

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)();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template