0

I've written a array function to draw openGL code outside without the need to add the function in the Windows' mainloop every time a new function has been made.

It works ok, but when I am pointing it to an public void function in another class, it is saying 'reference to non-static member function must be called'.

Code:

int main(int argc, const char * argv[])
{
    Window* win = new Window(800, 600, "3D Game Engine");
    Game game;
    win->draw[0] = a;
    win->draw[1] = game.render;

    win->MainLoop();
    delete win;
}

Draw function:

typedef void (*function_ptr)(int);

function_ptr *draw = (function_ptr*)malloc(sizeof(function_ptr));

Are there ways to call it?

Thanks

2
  • Look at std::function. Commented May 6, 2017 at 20:44
  • Could you please post the definition of the "Window" class - especially of the "draw" array? Commented May 6, 2017 at 20:47

1 Answer 1

2

The problem you have is the following one:

void (*function_ptr)(int);

Is a pointer to a function with one argument of the type int.

If you have a method in a class like this:

class exampleClass
{
public:
    void example(int a);
};

A C++ compiler will internally generate a function with an implicit this argument - just like this:

void exampleClass@example(exampleClass *this, int a);

(Internally most C++ compilers use illegal characters like @ in these functions' names - however this does not matter here.)

Therefore you normally cannot assign class methods to this kind function pointers. You would assign a function of the type (exampleClass *,int) to a function pointer of the type (int).

To avoid this the compiler normally does not allow you to store class methods in function pointers at all.

"At all" means that the compiler will also not allow you to use a function pointer of the correct internal type:

void (*function_ptr_2)(exampleClass *, int);
exampleClass y;

/* Not supported by the compiler although it is
 * theoretically possible: */
function_ptr_2 x1 = exampleClass::example; 
function_ptr_2 x2 = y.example; 

Unfortunately my C++ knowledge is not good enough so I cannot tell you if and how Angew's solution (std::function) works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.