What is a Callback in C++?

A callback is:

A function passed to another function so it can be called later.


Simple Real-Life Analogy

Suppose you order food online:

"Call me when food arrives"

Your phone number is the callback.

Restaurant calls you later.


In Programming

You give a function to another function.

That function gets executed later.


Simple Callback Example

#include <iostream>
#include <functional>

using namespace std;

void finished()
{
cout << "Task Finished!" << endl;
}

void process(function<void()> callback)
{
cout << "Processing..." << endl;

callback();
}

int main()
{
process(finished);

return 0;
}

Output

Processing...
Task Finished!

How it works


1. Callback function

void finished()

This function will be called later.


2. process() accepts callback

function<void()> callback

means:

Accept any function:
- no arguments
- returns void

3. Execute callback

callback();

calls:

finished();

Callback Flow

main()
|
v
process(finished)
|
v
callback()
|
v
finished()

Why callbacks are useful

Callbacks are heavily used in:

  • GUI buttons
  • networking
  • threads
  • timers
  • event systems
  • async programming

Example: Button Click

When button clicked
→ call this function

Example: Download Finished

Download complete
→ call callback

Callback with Lambda

Modern C++ usually uses lambdas.


Example

#include <iostream>
#include <functional>

using namespace std;

void process(function<void()> callback)
{
cout << "Working..." << endl;

callback();
}

int main()
{
process([]()
{
cout << "Lambda Callback!" << endl;
});

return 0;
}

Output

Working...
Lambda Callback!

Callback with Parameters

#include <iostream>
#include <functional>

using namespace std;

void calculate(int a, int b,
function<void(int)> callback)
{
int result = a + b;

callback(result);
}

int main()
{
calculate(10, 20,
[](int result)
{
cout << "Result: "
<< result << endl;
});

return 0;
}

Output

Result: 30

Your Earlier bind Example

You had:

function<void()> func =
bind(&ReadFile::replaceAndSave1, &rf);

This creates a callback.

Later:

func();

calls:

rf.replaceAndSave1();

Real-World Thread Callback Example

thread t(callbackFunction);

Thread executes callback later.


Event System Example

Mouse Clicked
→ callback function runs

Timer Example

Wait 5 seconds
→ callback runs

Modern C++ Preferred Style

Today developers prefer:

  • lambdas
  • std::function

instead of old C-style function pointers.


Old Style Callback

void (*callback)();

Modern Style

function<void()>

Cleaner and safer.


Final Understanding

A callback is simply:

A function you give to another function
to execute later.

It is fundamental in:

  • async programming
  • GUI applications
  • event-driven systems
  • multithreading
  • networking
  • robotics systems