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;
}
1

1 Answer 1

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)()
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.