Object-Oriented Programming

Callbacks

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Generalizing a Sort

C++ Library Equivalents

Callback

  • A callback is a bit of computation that a function/method can call when appropriate in the implemented algorithm
  • They permit customization of computation in a function/method
  • Not a new programming mechanism

Common Control Flow

Callback Control Flow

Control Flow Comparison

Callback Arguments

  • free functions, function pointers
  • lambda functions, anonymous functions
  • functors, class that acts like a function
  • methods, pointers to member functions

Example: Directory Traversal Iterator

  • Assume that Directory provides an iterator similar to std::vector
  • Client has to know how to use the iterator
  • Client calls Directory methods
  • Directory methods do not call the client
  • Have to know the methods available from Directory

Example: Directory Traversal Callback

  • Only one call to traverse the directory
  • Each call to traverse can take a different callback
  • Client calls traverse()
  • The method traverse() calls the client's outputFilename()
  • The callback is provided the filename via a parameter that the traverse() calls each pass
  • Only the parameters are available to the callback
  • Very useful when processing is quite complex, and it may be inefficient to save state and return each step
  • The implementation of Directory::traverse() would probably not use an iterator, but native functions/methods to the problem

Example: Directory Traversal Callback Constructor

  • Only one call to traverse the directory
  • Callback is set up in the constructor, so only one callback is possible per object
  • Client calls intermediate method DirectoryProcessor::process()
  • DirectoryProcessor::process() calls traverse()
  • The method traverse() calls the client's outputFilename()
  • So DirectoryProcessor code can work without knowing the code in the outputFilename()

Example Comparison