How to call through a member function pointer?

C++Function Pointers

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

Today, the canonical way is using the std::invoke function template, especially in generic code. Please note, that the member function pointer comes first:

import <functional>;

std::invoke(pcat, bigCat);

What you get: Unified calling syntax for virtually anything, that is invocable.

Overhead: none.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNayana AdassuriyaView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow
Solution 2 - C++neonxcView Answer on Stackoverflow