Polymorphism
Polymorphism - poly means many and morphs means forms. Polymorphism is the ability of an object to have more than one forms. For example, we have two or more objects from the same base class with methods with same name but their implementation is different.
For example: When we use "+" operator with integers it performs addition but when we use it with string, it does concatenation.
Types
There are two types of Polymorphism:
- Static/early binding or compile time Polymorphism.
- Dynamic/late binding or run time Polymorphism.
We have to use inheritance in order to achieve polymorphism. Inherited methods with same name performs different tasks. For example, we have a parent class animal and it has makeSound method but we have animals which make different sounds. Lion roars and dog barks. Therefore, we redefine makeSound method in lion class and dog class.
Compile time polymorphism
Compile time polymorphism is achieved with the help of method overloading and operator overloading. In this tutorial, we will discuss only about function overloading.
Run time polymorphism
Run time polymorphism is achieved with the help of virtual functions and dynamic binding.
Virtual Functions
A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. They are declared with the "virtual" keyword.
Overloading and overriding are two different terms.
| Overloading | Overriding |
|---|---|
| In overloading, functions have same name and their return types may or may not be different. | In over-riding, we redefine the function in derived class. The overriding functions have same name. |
| They have different number of parameters or if number of parameters is same their data type or sequence must be different. | Method overriding occurs only when the names and the type signatures of the two methods are identical. |
Practice Exercises
Complete these exercises to reinforce your learning and earn XP