C++ Polymorphism

What is polymorphism?

  • Polymorphism means having many forms or we can say we can define the polymorphism as the ability to display a message in many form.
  • It happens when there is a hierarchy of classes and they are related by inheritance. It also means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
  • Let us have a look at the real life example to understand polymorphism, like a person can have different characteristic at the same time.
  • Like a woman can behave as a mother, a wife and a employee at the same time so, a same person posses different behavior in different situations. This is known as polymorphism.

Types of Polymorphism

In C++, polymorphism can be divided into two types:

  • Compile Time Polymorphism
  • Runtime Polymorphism

Compile Time Polymorphism:

The compile time polymorphism can be achieved by function overloading or by operator overloading. The overloaded functions are invoked by matching the type and number of arguments and this is done at the compile time so, compiler selects the appropriate function at the compile time. The operator overloading is also known as static binding.

Function Overloading

When there are multiple functions with same name but have different parameters then these functions are said to be overloaded. They can be overloaded by change in number of arguments or change in type of arguments.

Let us have a look at the example:

Operator Overloading

  • In C++, operator overloading is a compile time polymorphism in which the operator is overloaded to provide the special meaning to the user defined data type.
  • It is used to overload the operator in C++ and perform the operation on the user defined data type.

Let us have a look at the example:

Runtime Polymorphism:

The runtime polymorphism is achieved when the object method is invoked at the runtime instead of compile time. It is achieved by method overriding which is also known as dynamic binding.

Function Overriding

The function overriding occurs when a derived class has a definition for one of the member functions of the base class. The base function is said to be overridden.

Let us have a look at the example:

Difference between Compile Time Polymorphism and Runtime Polymorphism

Compile Time Polymorphism Runtime Polymorphism
The function is invoked at the compile time. The function is invoked at the runtime.
It is known as overloading, early binding and static binding. It is also known as overriding, dynamic binding and late binding.
It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
It is less flexible. It is more flexible.
It provides fast execution. It provides slow execution.


Share this website !!!
Facebook Twitter Linkedin