Home > Backend Development > C++ > How to Correctly Call a Member Function Using a Pointer in C ?

How to Correctly Call a Member Function Using a Pointer in C ?

Linda Hamilton
Release: 2024-12-24 04:32:13
Original
799 people have browsed it

How to Correctly Call a Member Function Using a Pointer in C  ?

Calling Through a Member Function Pointer

In C , member function pointers allow us to treat member functions like regular functions through pointers. However, certain syntax rules must be followed to avoid compilation errors.

Consider the following code, where we attempt to call the walk member function of the cat class using a member function pointer:

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

The above code fails to compile with the error "bigCat.*pcat(); statement doesn't compile." This occurs because there's a precedence issue with the syntax.

Member function pointers use the "." operator, while function calls use normal parentheses. The precedence of function calls is higher than that of the "." operator.

To fix the issue, additional parentheses are required to override the precedence rule:

(bigCat.*pcat)();
Copy after login

With this correction, the code will now properly call the walk function through the member function pointer.

The above is the detailed content of How to Correctly Call a Member Function Using a Pointer in C ?. 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