Firstly, let me clarify this question doesn't explain my doubt clearly. To set the context clear. I'm asking this question specifically with regard to function pointers in C/C++.
I know the difference between early binding and late binding and how it works. What I would like to understand is the following with one example using function pointers in C/C++:
In many textbooks, it has been mentioned :
advantage of late binding is that it is more flexible than early binding, because decisions about what function to call do not need to be made until run time.
Also, it mentions:
With late binding, the program has to read the address held in the pointer and then jump to that address. This involves one extra step, making it slightly slower.
#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;
}
here, there is no advantage of using late binding and early binding as in the example below should be preferred.
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;
Could someone explain with an easy example like below where late binding is advantageous and why should someone choose it over early binding?