4. Compile Time Polymorphism:-
For every function call compiler binds the call to one
function definition at compile time. This decision of
binding among several functions is taken by considering
formal arguments of the function, their data type and their
sequence.
There are two type of compile time polymorphism.
Function overloading.
Operator overloading
5. – Overloading:-
• Two or more methods with different
signatures.
– Overriding:-
• Replacing an inherited method with
another having the same signature.
6. Example of Function overloading
/* C++ Program to return absolute value of variable types
integer and float using function overloading */
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
7. cout<<"Absolute value of "<<a<<" =
"<<absolute(a)<<endl;
cout<<"Absolute value of "<<b<<" = "<<absolute(b);
return 0;
}
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
Output:-
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
8. Run time Polymorphism
C++ allows binding to be delayed till run time. When you
have a function with same name, equal number of arguments
and same data type in same sequence in base class as well
derived class and a function call of form: base_class_type_ptr-
>member_function(args); will always call base class member
function. The keyword virtual on a member function in base
class indicates to the compiler to delay the binding till run
time.
Every class with atleast one virtual function has a vtable that
helps in binding at run time.
9. Run time polymorphism is also known as Dynamic binding
and Also known as late binding.
– In Dynamic binding Calls to overridden methods are
resolved at execution time, based on the type of object
referenced
10. Example of run time polymorphism:
class Base
{
public:
virtual void display(int i)
{ cout<<"Base::"<<i; }
};
class Derv: public Base
{
public:
void display(int j)
{ cout<<"Derv::"<<j; }
};
int main()
{
Base *ptr=new Derv;
ptr->display(10);
return 0;
}
Output: Derv::10