Will Anderson
Will Anderson

Reputation: 113

C++ Calling Functions from an Array of Function Pointers

I'm using function pointers stored in an array with a typedef defining the pointer and I'm a little lost on how I'm supposed to call the function.

here's the Menu.h part:

typedef void( Menu::*FunctionPointer )();

FunctionPointer* m_funcPointers;

here's the Menu.cpp part:

Menu::Menu()
    : m_running( true )
    , m_frameChanged( true )
    , m_currentButton( 0 )
    , m_numOfButtons( k_maxButtons )
    , m_menuButtons( new MenuButton[k_maxButtons] )
    , m_nullBtn( new MenuButton( "null", Vector2( -1, -1 ) ) )
    , m_frameTimer( 0 )
    , m_funcPointers( new FunctionPointer[k_maxButtons])
{
    m_timer.start();
    clearButtons();
    mainMenu();
}

void Menu::enterButton()
{
    m_funcPointers[m_currentButton]();//Error here
}

void Menu::mainMenu()
{
    m_funcPointers[0] = &Menu::btnPlay;
    m_menuButtons[0] = MenuButton("Play", Vector2(0, 0));

    m_funcPointers[1] = &Menu::btnHiScores;
    m_menuButtons[1] = MenuButton("HiScores", Vector2(0, 1));

    m_funcPointers[2] = &Menu::btnExit;
    m_menuButtons[2] = MenuButton("Exit", Vector2(0, 2));
}
void Menu::btnPlay()
{
    StandardGame* game = new StandardGame();

    game->play();

    delete game;
}

m_currentButton is an integer used as the index. I'm not sure how to actually call the function as the above line gives me this error:

**C2064 term does not evaluate to a function taking 0 arguments**

and visual studio give me this :

expression preceding parentheses of apparent call must have (pointer-to-) function type

I don't know how to solve the above problem and whether it's due to how I'm calling the function or how I'm storing it. Thanks in advance.

Upvotes: 1

Views: 1887

Answers (1)

eerorika
eerorika

Reputation: 238351

Calling Functions from an Array of Function Pointers

You call a function pointer in an array the same way as you would call a function that is not in an array.

Your problem isn't how to call a function pointer in an array as such. Your problem that you're trying to call a member function pointer as if it were a function pointer.

You can call a member function pointer like this:

Menu menu; // you'll need an instance of the class
(menu.*m_funcPointers[m_currentButton])();

Edit for the new example code: Since you're in a member function, perhaps you intend to call the member function pointer on this:

(this->*m_funcPointers[m_currentButton])();

If you find the syntax painful to read, I won't blame you. Instead, I'll suggest using std::invoke instead (available since C++-17):

std::invoke(m_funcPointers[m_currentButton], this);

Upvotes: 3

Related Questions