Early Binding And Late Binding

Introduction

Binding refers to the process that is used to convert identifiers (such as variable and function names) into machine language addresses.

Early Binding

Early binding means the compiler is able to directly associate the identifier name (such as a function or variable name) with a machine address.

Example

#include <iostream>
using namespace std;
 
int Add(int nX, int nY)
{
    return nX + nY;
}
 
int Subtract(int nX, int nY)
{
    return nX - nY;
}
 
int Multiply(int nX, int nY)
{
    return nX * nY;
}
 
int main()
{
    int nX;
    cout << "Enter a number: ";
    cin >> nX;
 
    int nY;
    cout << "Enter another number: ";
    cin >> nY;
 
    int nOperation;
    do
    {
        cout << "Enter an operation (0=add, 1=subtract, 2=multiply): ";
        cin >> nOperation;
    } while (nOperation < 0 || nOperation > 2);
 
    int nResult = 0;
    switch (nOperation)
    {
        case 0: nResult = Add(nX, nY); break;
        case 1: nResult = Subtract(nX, nY); break;
        case 2: nResult = Multiply(nX, nY); break;
    }
 
    cout << "The answer is: " << nResult << endl;
 
    return 0;
}

Late Binding

In some programs, it is not possible to know which function will be called until runtime (when the program is run). This is known as late binding.
In C++, one way to get late binding is to use function pointers.

#include <iostream>
using namespace std;
 
int Add(int nX, int nY)
{
    return nX + nY;
}
 
int Subtract(int nX, int nY)
{
    return nX - nY;
}
 
int Multiply(int nX, int nY)
{
    return nX * nY;
}
 
int main()
{
    int nX;
    cout << "Enter a number: ";
    cin >> nX;
 
    int nY;
    cout << "Enter another number: ";
    cin >> nY;
 
    int nOperation;
    do
    {
        cout << "Enter an operation (0=add, 1=subtract, 2=multiply): ";
        cin >> nOperation;
    } while (nOperation < 0 || nOperation > 2);
 
    // Create a function pointer named pFcn (yes, the syntax is ugly)
    int (*pFcn)(int, int);
 
    // Set pFcn to point to the function the user chose
    switch (nOperation)
    {
        case 0: pFcn = Add; break;
        case 1: pFcn = Subtract; break;
        case 2: pFcn = Multiply; break;
    }
 
    // Call the function that pFcn is pointing to with nX and nY as parameters
    cout << "The answer is: " << pFcn(nX, nY) << endl;
 
    return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.