Polymorphism

Merriam Webster defines ‘polymorphism’  as the ‘quality or state of existing in or assuming different forms’. In simpler terms, polymorphism is the ability of a message/data to be interpreted in more than one form. Thus, one interface can be used in different situations.

There are two types of polymorphism:

When the arguments of methods are resolved during compilation stage, it is called Static Binding or Early Binding of arguments. Alternatively, it is also called Compile Time Polymorphism. This type of polymorphism is achieved by overloaded functions and operators.

Overloading means having two or more meanings and enforces polymorphism in a program.

  • Overloaded Functions

A function with the same name having several different definitions, which can be distinguished by the number and types of arguments is said to be overloaded. This process is known as function overloading.

It reduces the number of comparisons in a program, reduces its length and thus, makes it faster.

  • Overloaded Operators

An operator capable of carrying out more than one action is called an overloaded operator. For example, the addition operator with numbers carries out addition and while the same ‘+’ sign can be used for concatenation of strings too. For example:

5 + 7 = 12

‘A’ + ‘BC’ = ‘ABC’

When the arguments of methods are resolved during run time, it is called Run Time Polymorphism. This type of polymorphism is achieved using virtual functions or through function overriding.

A virtual function is a method/member function of an abstract class whose functionality (or implementation details) are given through derived classes called concrete classes. A function is virtual when the keyword ‘virtual’ is used in the declaration of it.

For example, the function draw() is virtual in the class shape (abstract class) in C++

class shape

{

public:

   virtual void draw() = 0;  //virtual function (can be defined in the concrete class)

};

Now, there can be multiple definitions of draw() in the derived, concrete classes, thereby implementing polymorphism.

5 Replies to “Polymorphism”

Leave a Reply

Your email address will not be published. Required fields are marked *