How to create a callback function in C++

3 Answers

0 votes
#include <iostream>

// Using Function Pointers

// Callback function
void myCallback(int x) {
    std::cout << "myCallback() - Callback called with value: " << x << std::endl;
}

// Function that accepts a callback
void process(int value, void (*callback)(int)) {
    std::cout << "process() - Processing value: " << value << std::endl;
    
    callback(value); // invoke callback

    // Call → means to execute a function.
    // Back → means the control of execution will return back to the main function later, after some other work is done.
}


int main() {
    process(234, myCallback); // pass function pointer
    
    std::cout << "after";
}



/*
run:

process() - Processing value: 234
myCallback() - Callback called with value: 234
after

*/

 



answered Nov 29, 2025 by avibootz
0 votes
#include <iostream>
#include <functional>

// Using std::function and Lambdas

void runTask(int value, std::function<void(int)> callback) {
    std::cout << "runTask() Running task with value: " << value << std::endl;
    callback(value);
}

int main() {
    runTask(234, [](int x){ std::cout << "Lambda callback: " << x << std::endl; });
    
    std::cout << "after";
}


/*
run:

runTask() Running task with value: 234
Lambda callback: 234
after

*/

 



answered Nov 29, 2025 by avibootz
0 votes
#include <iostream>

// Using Functors (Objects with operator())

struct MyFunctor {
    void operator()(int x) {
        std::cout << "operator() Functor callback with: " << x << std::endl;
    }
};

void execute(int value, MyFunctor callback) {
    std::cout << "execute() Executing with value: " << value << std::endl;
    
    callback(value);
}

int main() {
    MyFunctor f;
    
    execute(234, f);
    
    std::cout << "after";
}



/*
run:

execute() Executing with value: 234
operator() Functor callback with: 234
after

*/

 



answered Nov 29, 2025 by avibootz
...