callback function clarification

Hi.

I didn't understand the concept and core uses of callback function(Except making the code more concise and readable).
i understand that this is a function A that pass to another function B as argument:

B(A) {

}

but why not to simply call A inside B?


B {

A();

}
Last edited on
Lets take one example function, the std::sort https://cplusplus.com/reference/algorithm/sort/
More specifically, the second overload:
1
2
template <class RandomAccessIterator, class Compare>
void sort( RandomAccessIterator first, RandomAccessIterator last, Compare comp );


It is like you function B(A comp). It has been written by the library authors.

Now, you have objects that you want to sort, and you don't want to sort with lhs < rhs.
How do you do that?

You give the std::sort a callback function (functor, function object) A that the std::sort will call to determine whether two objects are already in correct order or not.

The authors of std::sort can't nor need to know that function.


The first overload of std::sort:
1
2
template <class RandomAccessIterator, class Compare>
void sort( RandomAccessIterator first, RandomAccessIterator last );

does "simply" call some "function", but that is not entirely trivial either.
or to put it another way, it really does just call A inside B, it just does it via a pointer.
that way, the pointer can be to whatever function you need, interchangeable parts. Keeping the sort example, that lets you sort your special user defined type in multiple ways, perhaps by timestamp, or some numeric index, or a string, or even a combination of those, by string first and if those are equal, by timestamp, or whatever.
The pointer gives you a layer of flexibility that does not exist when you have a straight up this calls that approach.
but why not to simply call A inside B?

The point of a callback, is that you might not want B() to always call A(). B() might be a function designed to do something generic, but then to call out to some other function that might be different in different circumstances, depending on where it's called from, so you want the calling code to tell B() what to call.

Often, this happens in library functions. The library function will be written to perform a general task that might be used in lots of places, but is designed to be customisable, so that a developer can use the function, and supply a callback function to do something specific to the application being developed.

keskiverto's example of std::sort is a good one. The std::sort() function is generic - it does the work of sorting objects into an order, in (presumably) an efficient way. But the callback allows users to specify exactly how to determine that order for their own needs, by passing in a callback function.

Callbacks allow you to write a function for general use, but to allow the person calling the function to supply behaviour for a specific call.
Topic archived. No new replies allowed.