Handmade Hero»Forums»Code
Mustafa Al-Attar
19 posts
Working in a software company since 2008 and still. Has been working on an rpg in C++ with OpenGL since 2015 and still.
Calling function using array of function pointers
Hi there...

I don't seem to figure out the correct syntax for calling a function that has its pointer stored in an array.

The following is the code sample:

// define function pointers
typedef void(MainGame::*FunctionPointer)(void*);

// we could have 4 rendering functions.
FunctionPointer RenderFunctions[4];

RenderFunctions[0] = &MainGame::GameRender; // normal game rendering.
RenderFunctions[1] = &MainGame::SplashRender; // render the splash screen.
RenderFunctions[2] = &MainGame::TitleScreenRender; // render the title screen.
RenderFunctions[3] = &MainGame::RenderMapDesigner; // render the designer.

...

FunctionPointer F = (RenderFunctions[CurrentRenderStage]);

(*F)(nullptr); // this is the only statement that does not compile.


The error message I am getting from visual studio is: Operand of '*' must be a pointer.

Any help is highly appreciated. :)

yours sincerely.
mkaatr
Mustafa Al-Attar
19 posts
Working in a software company since 2008 and still. Has been working on an rpg in C++ with OpenGL since 2015 and still.
Calling function using array of function pointers
Hi there...

It seems after trying different combinations and searching, I found out how to perform such call. It should be:

(this->*F)(nullptr);


yours sincerely
mkaatr

:cheer:
105 posts
Calling function using array of function pointers
Since the functions are members of a class, they need to be called on an instance of the class (i.e. member functions have a different type than free functions).

You would call it like this:
1
2
3
MainGame mainGame;
...
(mainGame.*F)(nullptr);


or if the instance is a pointer,
1
(mainGame->*F)(nullptr);
Mustafa Al-Attar
19 posts
Working in a software company since 2008 and still. Has been working on an rpg in C++ with OpenGL since 2015 and still.
Calling function using array of function pointers
Thanks alot.

The problem is solved.