Loading...
C++ Polymorphism

C++ Polymorphism

In this tutorial, we will learn about Polymorphism in C++ programming with the help of examples.

Polymorphism

The word polymorphism means having many forms. Polymorphism is an important concept of object-oriented programming. It simply means more than one form. That is, the same entity (function or operator) behaves differently in different scenarios.
A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations.

For example:- The + operator in C++ is used to perform two specific functions. When it is used with numbers (integers and floating-point numbers), it performs addition.

int a = 5;
int b = 6;
int sum = a + b;    // sum = 11

And when we use the + operator with strings, it performs string concatenation. For example,

string firstName = "Justin ";
string lastName =  Bieber";

// name = "Justin Bieber"
string name = firstName + lastName;

In C++ polymorphism is mainly divided into two types:

We can implement polymorphism in C++ using the following ways:

  1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.
  2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

C++ Function Overloading

In C++, we can use two functions having the same name if they have different parameters (either types or number of arguments). then these functions are said to be overloaded. And, depending upon the number/type of arguments, different functions are called.

Example 1: C++ program to overload sum() function

#include <iostream>
using namespace std;

// Function with 2 int parameters
int sum(int num1, int num2) {
    return num1 + num2;
}

// Function with 2 double parameters
double sum(double num1, double num2) {
    return num1 + num2;
}

// Function with 3 int parameters
int sum(int num1, int num2, int num3) {
    return num1 + num2 + num3;
}

int main() {
    // Call function with 2 int parameters
    cout << "Sum of Two Integers Numbers = " << sum(4, 4) << endl;

    // Call function with 2 double parameters
    cout << "Sum of Two Decimal Numbers = " << sum(5.5, 4.5) << endl;

    // Call function with 3 int parameters
    cout << "Sum of 3 Integer Numbers = " << sum(5.5, 6.5, 6) << endl;

    return 0;
}

Output

Sum of Two Integers Numbers = 8
Sum of Two Decimal Numbers= 10
Sum of 3 Integer Numbers = 18

Here, we have created 3 different sum() functions with different parameters (number/type of parameters). And, based on the arguments passed during a function call, a particular sum() is called.

It's a compile-time polymorphism because the compiler knows which function to execute before the program is compiled.

To learn more about, visit our C++ Function Overloading tutorial.


C++ Operator Overloading

In C++, we can overload an operator as long as we are operating on user-defined types like objects or structures. We cannot use operator overloading for basic types such as int, double, etc.

Operator overloading is basically function overloading, where different operator functions have the same symbol but different operands. And, depending on the operands, different operator functions are executed.

For example:-

Example 2: C++ program to overload ++ when used as prefix

#include <string>
using namespace std;
class Count {
   private:
    int value;

   public:
    // Constructor to initialize count to 2
    Count() : value(2) {}

    // Overload ++ when used as prefix
    void operator ++() {
        value = value + 2;
    }
    void display() {
        cout << "Count: " << value << endl;
    }
};

int main() {
    Count cnt1;

    // Call the "void operator ++()" function
    ++cnt1;

    cnt1.display();
    return 0;
}

Output

Count: 4

Here, we have overloaded the ++ operator, which operates on objects of Count class (object cnt1 in this case).

We have used this overloaded operator to directly increment the value variable of cnt1 object by 2.

It is also a compile-time polymorphism because the compiler knows which function to execute before the program is compiled.

To learn more, visit our C++ Operator Overloading tutorial.


C++ Function Overriding

In C++ inheritance, we can have the same function in the base class as well as its derived classes.

Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

For example:-

Example 3: C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
   public:
    virtual void print() {
        cout << "Display Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Display Derived Function" << endl;
    }
};

int main() {
    Derived d1;

    // Call print() function of Derived class
    d1.print();

    return 0;
}

Output

Display Derived Function

Here, we have used a print() function in the Base class and the same function in the Derived class

When we call print() using the Derived object d1, it overrides the print() function of Base by executing the print() function of the Derived class.

It's a runtime polymorphism because the function call is not resolved by the compiler, but it is resolved in the runtime instead.

To learn more, visit our C++ Function Overriding tutorial.


C++ Virtual Functions

A virtual function is another way of implementing run-time polymorphism in C++. It is a special function defined in a base class and redefined in the derived class. To declare a virtual function, you should use the virtual keyword. The keyword should precede the declaration of the function in the base class.

Using virtual functions in the base class ensures that the function can be overridden in these cases. Thus, virtual functions actually fall under function overriding.

For example:-

Example 4: C++ program to demonstrate the use of virtual functions

#include <iostream>
using namespace std;

class Base {
   public:
    virtual void print() {
        cout << "Display Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Display Derived Function" << endl;
    }
};

int main() {
    Derived d1;

    // pointer of Base type that points to derived1
    Base* b1 = &d1;

    // calls member function of Derived class
    b1->print();

    return 0;
}

Output

Display Derived Function

Here, we have used a virtual function print() in the Base class to ensure that it is overridden by the function in the Derived class.

Virtual functions are runtime polymorphism.

To learn more, visit our C++ Virtual Functions tutorial.


Why Polymorphism?

Polymorphism allows us to create consistent code. For example,

Suppose we need to calculate the area of a circle and a square. To do so, we can create a Shape class and derive two classes Circle and Square from it.

In this case, it makes sense to create a function having the same name calculateArea() in both the derived classes rather than creating functions with different names, thus making our code more consistent.


Compile time vs Run time Polymorphism

Compile time polymorphism Run time polymorphism
The function to be invoked is known at the compile time. The function to be invoked is known at the run time.
It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding.
Overloading is a compile time polymorphism where more than one method is having the same name but different number of parameters or the type of the parameters. Overriding is a run time polymorphism where more than one method is having the same name, number of parameters and the type of the parameters.
It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.
It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Polymorphism in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Function Overloading.

- Related Topics