Tutorial Study Image

Polymorphism in C++


June 3, 2023, Learn eTutorial
319

This article defines polymorphism in C++ and lists several kinds of polymorphism. Examples and source code are used to describe each type of polymorphism. The distinction between compile-time as well as run-time polymorphism is covered in the tutorial. Code and examples are used in order to teach the concepts of virtual and pure virtual functions.

Polymorphism: What is it?

Polymorphism is derived from the words "poly" (many) and "morphs" (forms), which together indicate many forms. When an object or function behaves differently under different circumstances, this is known as polymorphism in C++. The ability of the message to be displayed in multiple forms is how we can define polymorphism in simple words. Being a father, a spouse, and an employee all at once makes one feel like a man. As a result, the same person behaves differently depending on the circumstance. Polymorphism is the term for this. One of the key components of Object-Oriented Programming is polymorphism.

Let's look at a real-world illustration of how the term "right" can have various meanings depending on the situation.

  • You are right. Right here in the sentence signifies correct.
  • Please turn to the right, please. In this sentence, the term "right" refers to the proper direction.

A simple example of polymorphism in C++

Program to add two numbers, using the + operator in C++


#include <bits/stdc++.h>
using namespace std;

int main() {
    int a = 20;
    int b = 50;
    
    cout << "Value of a + b is: " << a + b;
 return 0;
}
 

Output:


Value of a + b is: 70

When the operators + are used to combine the values a=20 and b=50 in the above example, the output Value of a + b is 70.

However, two-string operands can also be concatenated using the + operator.

How two strings are concatenated using the + operator in C++


#include <bits/stdc++.h>
using namespace std;

int main() {
    string a = "Poly";
    string b = "morphism";
    
    cout << "So a + b is: " << a + b;
 return 0;
}
 

Output:


So a + b is: Polymorphism

The output value of a+b is "Polymorphism" in the example above because + is used to combine/ concatenate the strings a= Poly and b = morphism.

Types of Polymorphism

In C++, there are mainly 2 types of polymorphism:

  1. Compile Time Polymorphism
  2. Runtime polymorphism
Polymorphism in C++
  1. Compile Time Polymorphism

    Another name for compile-time is static or early binding. By overloading an operator or function, compile-time polymorphism is achieved.

    Why is it referred to as compile-time polymorphism?

    Just by comparing the type of the parameters as well as the number of parameters, overloaded functions are invoked. The compiler has access to this kind of data during compilation. As a result, the C++ compiler will select the appropriate function at compilation time.

    The following categories of compile-time polymorphism are available in C++:

    Polymorphism in C++

    Function Overloading

    When two functions with the same name and different parameters are used, distinct functions are invoked based on the number and type of parameters. Function overloading is what's happening here.

    The following two situations can lead to function overloading:

    • The functions have the same name and return type, but their argument types are different.
    • The functions have the same name and return type, but they have different numbers of arguments.

    Example program for function overloading

    
    #include <bits/stdc++.h>
    using namespace std;
    class Temp
    {
        private:
            int x = 20;
            double x1 = 20.1;
        public:
            void add(int y)
            {
               cout << "The value of x + y is: " << x + y << endl;
            }
            // differ in the type of argument
            void add(double d)
            {
               cout << "Value of x1+d is: " << x1 + d << endl;
            }
            //differ in  number of arguments
            void add(int y, int z)
            {
               cout << "The value of x+y+z is: " << x + y + z << endl;
            }
    };
    int main() {
        Temp t1;
        t1.add(20);
        t1.add(20.1);
        t1.add(13,14);
     
        return 0;
    }
     
    

    Output:

    
    The value of x + y is: 40
    Value of x1+d is: 40.2
    The value of x+y+z is: 47
    

    Explanation of the program

    The add function in the above example is overloaded. Object t1 belongs to the class Temp. Add (20). This will call the void add (int y). t1.add(20.1), will be calling the void add (double d). t1.add(13,14), will be calling the void to add (int y, int z). When the type, as well as a number of arguments, match, the overloaded functions, are invoked. The compiler chooses the appropriate function since this information is accessible at the time of compilation.

    Operator Overloading

    Operator overloading refers to the updating of an operator to support user-defined data types (objects, etc.). At least one operand must be of a user-defined data type in order to use operator overloading.

    Some of the operations in C++ that can be overloaded are as follows:

    Arithmetic operators : -, +, /, *,% and -=, +=, /=, *=, %=

    Boolean Algebra : !=, ==, >, <, >=, <=, &&, ||

    Bit Manipulation : &, |, ^, <<, >>, and |=, &=, >>=, <<=, ^=

    Memory Management : new[], delete[], delete, new

    Example program for operator overloading

    
    #include<iostream>
    using namespace std;
    
    class Count
    {
        int x;
        public:
         //  constructor
        Count(int X = 0)
        {
            this -> x = X;
        }
        // Overloading the ++ operator
        Count operator++()
        {
           Count c ;
           
           c.x = ++x;
           
           return c;
        }
        // print value of x
        void print()
        {
            cout << x << endl;
        }
        
    };
    
    int main()
    {
        Count c1(22);
        
        cout << "So before using ++ operator: ";
        c1.print();
        
        Count c2 = ++c1;
        cout << "So after using ++ operator: ";
        c2.print();
        
    }
     
    

    Output:

    
    So before using ++ operator: 22
    So after using ++ operator: 23
    

    Explanation of the program

    The ++ operator is overloaded in the example above for a user-defined data type, as well as an object of a Count class.

    Count c1(22); generates an object of type Count, whose data member x will be set to a value of 22.

    Count c2 = ++c1, which invokes the ++ operator function on t1 and sets x to be 23.

  2. Runtime Polymorphism

    Polymorphism in C++

    When functions are invoked at runtime rather than compile-time, or when a call to an overridden method is dynamically resolved at runtime rather than compile-time, this phenomenon is known as runtime polymorphism. It is often referred to as dynamic binding or late binding.

    Function overriding and virtual functions are combined to create runtime polymorphism. The complete concept of virtual functions will be discussed in the next tutorial.

Compile-Time Polymorphism Vs. Run-Time Polymorphism

Compile-Time Polymorphism Run-Time Polymorphism

Which functions will be invoked is chosen at compile time.

Which function will be called is selected at runtime.

Early or static binding is another name for this.

late or dynamic binding is another name for this.

Function and operator overloading is mainly used in order to achieve it.

Function overriding and virtual functions are mainly used in order to achieve it.

Overloading is a type of compile-time polymorphism in which many methods with the same name but differing numbers or types of parameters are produced.

Runtime polymorphism known as "function overriding" occurs when many methods from a derived class share the same name, same number of parameters, as well as same type of parameters as their base class.

Because all decisions are made at the time of compilation, it executes more quickly.

Because everything is decided at run-time, the execution is slower.

Conclusion

In C++, polymorphism refers to when the same object or function behaves differently in various circumstances. There are two kinds of it: compile-time and runtime.

The function to be invoked in compile-time is determined only at compile-time. It is accomplished by overloading a function or operator.

The function that is called at compile time is determined at run time. Function overriding and virtual functions are used to achieve it.