Using function pointers

A function pointer is merely a pointer. This means that you can use it as a variable; you can return it from a function, or pass it as a parameter. For example, you may have some code that performs some lengthy routine and you want to provide some feedback during the routine. To make this flexible, you could define your function to take a callback pointer and periodically in the routine call the function to indicate progress:

    using callback = void(*)(const string&);      void big_routine(int loop_count, const callback progress)     {         for (int i = 0; i < loop_count; ++i)         {             if (i % 100 == 0)             {                 string msg("loop ");                  msg += to_string(i);                  progress(msg);             }             // routine         }     }

Here big_routine has a function pointer parameter ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.