Search code examples
c++pointersbinary-search-treevoid

Can You Explain This Void Pointer Inside Function Paramter?


Here is the code in question! I have not spent too much time with C++, and I'm implementing a Binary Search Tree.

void BST::Preorder(void(*visit)(const Node *))

Later on the function is called like this:

bst.Preorder(PrintNode)

With PrintNode being implemented as follows:

void PrintNode(const Node* n)
{
    cout << n->GetValue() << ",";
}

Asked to implement this Preorder function-- but I am very confused as to what's going on here. Can anyone please point me in the proper direction. Thank you.


Solution

  • So Preorder is a function that will iterate through all the nodes in the binary search tree (in a particular order) and do something at each node. So it's useful to write Preorder in such a way that the caller of Preorder can specify what is to be done at each node. That is the purpose of the visit parameter. It's a function (actually a function pointer) that Preorder should call at every node it visits. In the example you've been given each node is going to be printed, but by supplying a different function as the parameter to Preorder you could make it do something different.