Polymorphism in C++

Posted on

The time period Polymorphism get derived from the Greek phrase the place ‘poly’ + ‘morphos’ the place ‘poly’ means many and ‘morphos’ means types.


In programming background, polymorphism might be broadly divided into two elements. These are:

  • Static Polymorphism
  • Dynamic Polymorphism.

Polymorphism - Polymorphism in C++

Polymorphism is one other idea of object oriented programming (OOPs). The perspective which lies beneath this idea is “single interface having a number of implementations.” This supplies a single interface for controlling entry to a basic class of actions. Polymorphism might be gained in each methods:

  • compile time and
  • run time

A standard and easy instance of polymorphism is whenever you used >> and << as operator overloading in C++, for cin and cout statements respectively. This bitwise shift operator at the moment acts as a inclusion operator and its overloaded which means is outlined in iostream header file.

Static Polymorphism

In static polymorphism or early binding, there you’re going to get two sub classes like:

  • Operate overloading which is the method of utilizing the identical identify for 2 or extra capabilities.
  • Operator overloading which is the method of utilizing the identical operator for 2 or extra operands.

Code Snippet for Operate Overloading

Code snippet for Operator Overloading

It’s to be famous that perform overloading might be executed and is feasible solely primarily based on:

  • the return sort of that overloaded perform
  • the kind of parameters and its association
  • primarily based on the variety of parameters

Dynamic Polymorphism

This refers back to the entity which modifications its kind relying on circumstances at run time. This idea might be adopted as analogous to a chameleon altering its colour on the sight of an approaching object.

What’s a Digital Operate?

A digital perform might be outlined because the member perform inside a base class which you count on to redefine in derived lessons. For making a digital perform, it’s a must to precede your perform’s declaration inside the base class with a ‘digital’ key phrase.

Instance of easy methods to use digital perform

Instance: