Compile-time polymorphism
Till now we have seen how the concept of polymorphism is implemented using the overloaded function and overloaded operators.
Compile-time polymorphism is further divided in two types
(i). Function Overloading/Function polymorphism
(ii). Operator Overloading/Operator polymorphism
Function Overloading/Function polymorphism
Function Overloading is defined as the process of having two or more functions with the same name, but different in parameters is known as function overloading in C++.
In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because you don’t need to use different names for the same action.
The overloaded member functions are selected for invoking / execution by matching arguments both data types and number. This information is known to the compiler at the compile time and therefore the compiler is able to select the appropriate function for a particular call at compile time itself. This is called static binding / compile time binding / compile time polymorphism / static linking / early binding.
Early binding simply means that an object is bound to its function call at compile time.
Function Overloading examples:
Example:1
Sum of 2 ,3 and 4 nos.
Sol:
#include<iostream> using namespace std; int sum(int n1,int n2) { return(n1+n2); } int sum(int n1,int n2,int n3) { return(n1+n2+n3); } int sum(int n1,int n2,int n3,int n4) { return(n1+n2+n3+n4); } int main() { int a1,a2,a3,a4,a5; cout<<"Enter 4 nos "; cin>>a1>>a2>>a3>>a4; a5=sum(a1,a2); cout<<"Sum of 2 nos "<<a5<<endl; a5=sum(a1,a2,a3); cout<<"Sum of 3 nos "<<a5<<endl; a5=sum(a1,a2,a3,a4); cout<<"Sum of 4 nos "<<a5<<endl; return(0); }
Output:
Enter 4 nos 10
20
30
40
Sum of 2 nos 30
Sum of 3 nos 60
Sum of 4 nos 100
Example:2
prod of 2 ,3 and 4 nos.
Sol:
#include<iostream> using namespace std; int prod(int n1,int n2) { return(n1*n2); } int prod(int n1,int n2,int n3) { return(n1*n2*n3); } int prod(int n1,int n2,int n3,int n4) { return(n1*n2*n3*n4); } int main() { int a1,a2,a3,a4,a5; cout<<"Enter 4 nos "; cin>>a1>>a2>>a3>>a4; a5=prod(a1,a2); cout<<"prod of 2 nos "<<a5<<endl; a5=prod(a1,a2,a3); cout<<"prod of 3 nos "<<a5<<endl; a5=prod(a1,a2,a3,a4); cout<<"prod of 4 nos "<<a5<<endl; return(0); }
Output:
Enter 4 nos 1
2
3
4
prod of 2 nos 2
prod of 3 nos 6
prod of 4 nos 24