How is polymorphism achieved at compile time in C++

How is polymorphism achieved at compile time in C++

Polymorphism, in C++, is implemented through overloaded functions and overloaded operators. Function Overloading is also referred to as functional polymorphism. The same function can perform a wide variety of tasks. The same function can handle different data types. When many functions with the same name but different argument lists are defined, then the function to be invoked corresponding to a function call is known during compile time. When the source code is compiled, the functions to be invoked are bound to the compiler during compile time, as to invoke which function depending upon the type and number of arguments. Such a phenomenon is referred to early binding, static linking or compile time polymorphism.

For example:

#include <iostream.h>

//function prototype

int multiply(int num1, int num2);
float multiply(float num1, float num2);

void main()
{
//function call statements

int ans1=multiply(4,3);
// first prototype is invoked as arguments
// are of type int

float ans2 = multiply(2.5, 4.5);
//second prototype is invoked
//as arguments are of type float
}

The compiler checks for the correct function to be invoked by matching the type of arguments and the number of arguments including the return type. The errors, if any, are reported at compile time, hence referred to as compile time polymorphism.