Summary: In this tutorial, we will learn what polymorphism is and how many different types of it is in C++.

Introduction to Polymorphism in C++

Polymorphism is one of the main properties of an object-oriented programming language.

It allows a function have multiple forms depending on the situation.

Polymorphism according to the English dictionary means “the condition of occurring in several different forms”.

A real-life example of polymorphism is that a single person at the same time can be a father, a son, or an employee

Similarly, a function can perform different tasks depending on the conditions.

In C++, we can achieve Polymorphism in two ways:

  1. Static Polymorphism
  2. Dynamic Polymorphism

What is Static Polymorphism?

The polymorphism that happens during the compile time is known as static polymorphism.

It is also known as static linkage or early binding and is implemented by overloading functions in C++.

A simple example of static polymorphism:

#include <iostream>
using namespace std;

int add(int a, int b){
    return a+b;
}

double add(double a, double b){
    return a+b;
}

int main() {
    cout << add(5, 8) << endl;    //output 13
    cout << add(4.2, 2.3) << endl;    //output 6.5
    return 0;
}

In this example, we have defined two functions having the same name (i.e. add).

The compiler when scans the call statements in the main method, it link it to the appropriate add method on the based on the parameters during the compilation time.

Because linking of the call statement to the function happens during the compile-time, it is called static or early binding.

What is Dynamic Polymorphism?

The polymorphism that happens during the runtime of the program is known as dynamic programming.

It is also known as dynamic linkage or late binding and is implemented by overriding functions with the use of virtual functions.

A simple example of dynamic polymorphism is:

#include <iostream>
using namespace std;

class Animal{
public:
    virtual void canWalk(){
        cout << "The Animal can walk.";
    }
};

class Dog: public Animal{
public:
    virtual void canWalk(){
        cout << "The Dog can walk.";
    }
};

int main() {
    Dog dog;
    dog.canWalk();    //output The Dog can walk.
    return 0;
}

In this example, we are overriding the Animal class’s canWalk method in the Dog class.

In response to the dog.canWalk() call statement, the Dog class’s canWalk method gets invoked.

The decision to call the method of the Dog class instead of the Animal class is made during the runtime of the program. It is therefore called dynamic or late binding.

For more details, please go to the function overloading and function overriding posts.

Leave a Reply

8 + 10 =