Search code examples
c++linuxgccpointer-to-memberjump-table

function pointers in array (nix c++)


I'm getting a compiler error when I'm trying to initialize my array with function pointers. Without using a class I'm able to run the code fine, but when I incorporate the code in a class I'm getting the error. I suppose this is more of a problem with my understanding of class usage, the scope resolution operator, etc. Any help to get this resolved would be much appreciated.

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

#define F1 0
#define F2 1
#define F3 2

class A
{
private:
    bool Func1();
    bool Func2();
    bool Func3();

public:
    bool do_it(int op);
    typedef bool (A::*fn)(void);
    static fn funcs[3];

protected:

};

A::fn A::funcs[3] = {Func1, Func2, Func3};

int main()
{
    A Obj;
    cout << "Func1 returns " << Obj.do_it(F1) << endl;
    cout << "Func2 returns " << Obj.do_it(F2) << endl;
    cout << "Func3 returns " << Obj.do_it(F3) << endl;

    return 0;
}

bool A::do_it(int op)
{
    assert(op < 3 && op >= 0);
    return (this->*(funcs[op]))();
}

bool A::Func1() { return false; }
bool A::Func2() { return true; }
bool A::Func3() { return false; }

The compiler spits out:

15:35:31 **** Build of configuration Debug for project JT ****
make all 
make: Warning: File 'objects.mk' has modification time 7.3 s in the future
Building file: ../src/JT.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/JT.d" -MT"src/JT.o" -o "src/JT.o" "../src/JT.cpp"
../src/JT.cpp:141:41: error: cannot convert ‘A::Func1’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
 A::fn A::funcs[3] = {Func1, Func2, Func3};
                                         ^
../src/JT.cpp:141:41: error: cannot convert ‘A::Func2’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
../src/JT.cpp:141:41: error: cannot convert ‘A::Func3’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
src/subdir.mk:18: recipe for target 'src/JT.o' failed
make: *** [src/JT.o] Error 1

15:35:32 Build Finished (took 1s.64ms)

Solution

  • Use A::fn A::funcs[3] = {&A::Func1, &A::Func2, &A::Func3};