Binding refers to the process that is used to convert identifiers (such as variable and function names) into machine language addresses. Although binding is used for both variables and functions, in this lesson we’re going to focus on function binding.
#include <iostream>
void PrintValue(int nValue)
{
std::cout << nValue;
}
int main()
{
PrintValue(5); // This is a direct function call
return 0;
}
This is early binding.Early binding (also called static binding)
means the compiler is able to directly associate the identifier
name (such as a function or variable name) with a machine address.
Remember that all functions have a unique machine address.
So when the compiler encounters a function call, it replaces
the function call with a machine language instruction that tells
the CPU to jump to the address of the function.
int Add(int nX, int nY)
{
return nX + nY;
}
int main()
{
// Create a function pointer and make it point to the Add function
int (*pFcn)(int, int) = Add;
cout << pFcn(5, 3) << endl; // add 5 + 3
return 0;
}
This is late binding.
it is not possible to know which function will be called
until runtime (when the program is run). This is known as
late binding (or dynamic binding). In C++, one way to get
late binding is to use function pointers. To review function
pointers briefly, a function pointer is a type of pointer that
points to a function instead of a variable. The function that
a function pointer points to can be called by using the function
call operator (()) on the pointer.
|
Calling a function via a function pointer is also known as an indirect function call.
|