Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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

Related questions

...