Polymorphism
Polymorphism meaning having many forms.
In C++ there are two types of polymorphism
- Compile-time polymorphism
- Run-Time polymorphism
Compile time polymorphism
The binding happens at compile time, meaning based on the arguments the compiler tries to interpret the function call.
It can be observed with function overloading. Based on the type of arguments passed, the compiler decides which function to call.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int add(int a, int b) { | |
return a + b; | |
} | |
int add(int a, int b, int c) { | |
return a + b + c; | |
} | |
void main() | |
{ | |
/*depending on the number of the arguments passed | |
compiler decides which method to call | |
*/ | |
add(1,2); | |
add(1,2,3); | |
} |
Run time polymorphism
The binding happens at run time. Function over-riding is an example of Run-time polymorphism.
Here is a simple example of Run-time polymorphism.
In the above example, based on the type of the object the pointer is holding we would want the function to be called. If it is Dog pointer, then the Dog class's sound method is executed. This feature of the compiler to identify the type of object at run time and call the correct method is called Run time polymorphism. For this to occur the base class should have atleast one virtual function.
Here is a simple example of Run-time polymorphism.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
public: | |
//remove the virtual keyword here to avoid dynamic binding | |
virtual void sound() { | |
} | |
}; | |
class Cat :public Animal { | |
void sound() { | |
cout << "Meow" << endl; | |
} | |
}; | |
class Dog :public Animal { | |
void sound() { | |
cout << "Woof" << endl; | |
} | |
}; | |
void makesound(Animal*ptr) | |
{ | |
ptr->sound(); | |
} | |
int main() | |
{ | |
Animal*catptr = new Cat(); | |
Animal*dogptr = new Dog(); | |
makesound(catptr); | |
makesound(dogptr); | |
return 0; | |
} |
No comments:
Post a Comment