1

I will like to know, how to make a function where I define a function. And then I can call the defined function. Let me try with a example.

void funcToCall() {
    std::cout<<"Hello World"<<std::endl;
}

void setFuncToCall(void func) {
    //Define some variable with func
}

void testFuncCall() {
    //Call function that has been defined in the setFuncToCall
}

setFuncToCall(funcToCall()); //Set function to call
testFuncCall(); //Call the function that has been defined

I Hope that you understand what I am trying to do here. But I don't know how to bring It down to the right code :-)

0

3 Answers 3

4

You need a function pointer. It's easier to work with function pointers if you typedef them first.

typedef void (*FuncToCallType)();

FuncToCallType globalFunction; // a variable that points to a function

void setFuncToCall(FuncToCallType func) {
    globalFunction = func;
}

void testFuncCall() {
    globalFunction();
}

setFuncToCall( funcToCall ); //Set function to call,NOTE: no parentheses - just the name 
testFuncCall(); //Call the function that has been defined

As other answers have suggested you can use objects like functions, too. But this requires operator overloading (even if it remains hidden from you) and is typically used with templates. It gives more flexibility (you can set some state to the object before passing it to the function and the object's operator() can use that state) but in your case function pointers may be just as good.

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

Comments

2

What you want to use is a callback, and is has been answered her : Callback functions in c++

I would advise you to use std::tr1::function ( generalized callback )

1 Comment

Yes, I haven't thought about it, it's a better choice for C++ than my answer.
2

C syntax for function pointers is a bit weird, but here we go:

// this is a global variable to hold a function pointer of type: void (*)(void)
static void (*funcp)(void); 
// you can typedef it like this:
//typedef void (*func_t)(void); 
// - now `func_t` is a type of a pointer to a function void -> void

// here `func` is the name of the argument of type `func_t` 
void setFuncToCall(void (*func)(void)) { 
// or just: void setFuncToCall(func_t func) {
    //Define some variable with func
    ...
    funcp = func;
}

void testFuncCall(void) {
    //Call function that has been defined in the setFuncToCall
    funcp();
}

setFuncToCall(funcToCall);  // without () !
testFuncCall();

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.