Polymorphism

NOTE : – This Blog does not cover the complete Polymorphism; here we explain the general idea of polymorphism like what is polymorphism, how polymorphism works & conditions for polymorphism.

In this Blog we learn about polymorphism.

What is Polymorphism ?

Polymorphism is the one of the most essential feature of Object Oriented Programming

If we bifurcate the word Polymorphism, we get “Poly” means many and “Morphism” means form.

Thus, polymorphism means more than one form.

Polymorphism gives us the ability to write several versions of a function, each in a separate class. Then, when we call the function, the version appropriate for the object being referenced is executed. We see the same concept in our everyday language. We use one verb (function) to mean different things. For example, we say “open,” meaning to open a door, a jar, or a book; which one is determined by the context.

Similarly, in C++, we can call a function named printArea to print the area of a triangle or the area of a rectangle

To better understand the concept of polymorphism, we must first understand the concept of plug-compatible objects. An analogy with electrical devices may help

Assume we have two electrical devices (such as a table lamp and a television set). We have only one socket that can supply power to one of these devices at a time. Each device has a plug that can be inserted into the only socket. At time t1, we plug the lamp into the socket. At time t2, we unplug the lamp and plug the TV set in the socket. We can do so because the two devices are plug-compatible; their plugs follow the same standard. The interesting point about plug-compatible devices is that all get the same thing (electrical power) from the socket, but each does a different task.

Condition For Polymorphism :

We define the conditions for polymorphism in inheritance by comparing polymorphism with a plug.


Pointers or References
For comparison, we need something that plays the role of a socket that, once created, can accept plug-compatible objects. In C++, a pointer or a reference can play this role. We can define a pointer (or a reference) that can point to the base class; we can then let the pointer
point to any object in the hierarchy. For this reason, the pointer and reference variables are sometimes called polymorphic variables.
Exchangeable Objects
We need plug-compatible objects that play the role of devices. An object in an inheritance hierarchy plays this role.
Virtual Functions
We need something to play the role of power given to different devices that perform different tasks. This is done in C++ using virtual functions, which are modified by the keyword virtual. For example, we can have a print function in all classes, all named the same, but each printing differently.

For polymorphism, we need pointers (or references), we need exchangeable objects, and we need virtual functions.

Leave a comment