2

I am just learning function pointer and want to test how it works with member functions. The compilation of the following code fails at where it is marked.

# include <iostream>
# include <stdio.h>
using namespace std ;

class TMyClass {
public:
  int DoIt ( float a, char b, char c ) {
    cout << " TMyClass::DoIt " << endl ;
    return a + b + c ;
  }

  int DoMore ( float a, char b, char c ) {
    cout << " TMyClass::DoMore " << endl ;
    return a - b + c ;
  }

  int ( TMyClass::*pt2Member ) ( float, char, char ) ;

  int test_function_pointer ( ) {
    this->pt2Member = &TMyClass::DoMore ;
    int result = ( this -> *pt2Member ) ( 12, 'a', 'b' ) ; // wrong!
    // expected unqualified-id before "*" token

    return 0 ;
  }
} ;

int main () {
  TMyClass A ;
  A.test_function_pointer () ; 
  return 0 ;
}

I wonder how to make it work. Thanks!

0

2 Answers 2

5

What a difference a space makes:

int result = ( this ->* pt2Member ) ( 12, 'a', 'b' );
                 // ^^^

->* is an operator of its own.

See the fixed demo here please.

Sign up to request clarification or add additional context in comments.

Comments

0

This line:

int result = ( this -> *pt2Member ) ( 12, 'a', 'b' ) ; // wrong!

should have been:

int result = ( this ->*pt2Member ) ( 12, 'a', 'b' ) ; // wrong!

->* is an operator and you cannot insert spaces inside it as it splits it into two different operators: -> and *. This is similar to <<, >>, --, ++ which also cannot be split by spaces into two different tokens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.