0

I am trying to use function pointer in a c++ class but got an error.

#include <cstdio>
#include <iostream>
using namespace std;

class abc{
public:
    void hello(){
        printf("Hello world\n");
    }   
    abc(){
        void (*hw)(void);
        hw = &hello;
        hw();
    }
}

int main()
{
    abc ab;
    return 0;
}

Error

error: cannot convert ‘void (abc::*)()’ to ‘void (*)()’ in assignment

But the following code works for me which is in code base. Can anyone please help me to find out the difference?

void hello(){
    printf("Hello world\n");
}

int main()
{
    void (*hw)(void);
    hw = &hello;
    hw();
    return 0;
}
shantanu
  • 2,408
  • 2
  • 26
  • 56
  • Take a look at http://stackoverflow.com/questions/990625/c-function-pointer-class-member-to-non-static-member-function and http://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer – Rob11311 May 27 '14 at 16:09

1 Answers1

5

Function pointers are (unfortunately) completely different from method pointers, as the error is trying to indicate. This is because the object that the method works on needs to be passed in somehow, which is what makes methods fundamentally different from functions in the first place (and obviously affects how the call is done through the pointer). Method pointers are not even always the same size (and can be significantly larger than a function pointer) when multiple/virtual inheritance comes into play.

You need to declare a method pointer, and call it on behalf of an object of the right type using one of the esoteric .* or ->* operators:

class abc {
public:
    void hello(){
        printf("Hello world\n");
    }   
    abc() {
        void (abc::*hw)();
        hw = &abc::hello;
        (this->*hw)();  // or (*this.*hw)()
    }
}
Cameron
  • 96,106
  • 25
  • 196
  • 225
  • Thank you for quick reply. But the line 'hw = &hello' returns a compiler error 'function_pointer.cpp:10:15: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&abc::hello’ [-fpermissive]' – shantanu May 27 '14 at 16:32
  • 1
    @shantanu: Oops, I had forgotten that rule (some compilers are more lenient than others). The compiler is indeed right -- instead of `&hello` it should be `&abc::hello`. – Cameron May 27 '14 at 16:48