Polymorphism means same entity behaving differently at different times. Compile time polymorphism is also called as static binding. Compile time or static binding means Function body is bind to the function call at compile time itself. In C++ compile time polymorphism can be achieved using Function overloading and operator overloading.
Function overloading
Function overloading means, having multiple functions with same names. So how compiler does distinguishes between the multiple functions with same names. In function loading multiple functions can have same name but they differ on number of parameters order of parameters and type of parameters.
Number of parameters
|
1 2 3 4 5 |
Int Function(); Int Function(int param1); Int Function(int param1, int param2); |
Order of parameters:
|
1 2 3 4 5 |
int Function(int param1, float param2, char param3); int Function(, float param2, char param3,int param1); int Function( float param2, int param1, char param3); |
Types Of Parameters:
|
1 2 3 4 5 |
int Function(float param); int Function(int param); int Function(char param1); |
Note:
Functions cannot be overloaded based on function return type, as it may cause ambiguity. Compiler will give an error in this case.
|
1 2 3 4 5 6 7 8 9 |
int function(); float function(); void main(void) { Function(); // int return Function(); // float return; } |
Here its not possible to know which function body to be executed.
Overloading with Const member function :
There is another type of overloading, however it’s different than normal overloading and we can say its special.
We can declare a const member function which can be called on constant objects and it guarantess that it will not modify any member data.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class MyClass { Public: int getValue() const; int getValue(); }; MyClass myObj; myObj. getValue(); // Normal method will be called Const MyClass myConstObj; myConstObj. getValue(); // Const method will be called |
Function Overloading with templates:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
template <class T>; bool Min( T a, T b) { return( a < b); } Min <int> ( 10, 20); Min <float>( 1.5, 0.5) Min <char> ( ‘ Z’,’z’); </char></float></class> |
This is again special type of overloading; usually we have multiple functions declared with same name. However in templates we have just single function. At compile time based on parameter passed to function in angle brackets a data type specific template function Is generated. In the object code we have three different functions one for each int, char,float.
