×

Compile Time Polymorphism in C++

What is Polymorphism?

Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in real life is the simultaneous existence of many traits in one individual. A man simultaneously serves as a parent, a partner, and an employee. Therefore, the same person exhibits diverse behaviour depending on the circumstance. This is known as polymorphism. Polymorphism is one of the essential elements of object-oriented programming.

In C++, a polymorphic member function behaves differently based on the entity that calls or activates it. The Greek word polymorphism implies to have various forms. It happens when there is an inheritance-related hierarchy of classes.

What is Compile Time Polymorphism?

To create this form of polymorphism, either operators or functions must be overloaded. The overload functions are invoked when the type and number of arguments match. The data is available at compile time. This indicates that the C++ compiler will choose the appropriate function during compilation. Compile-time polymorphism can be achieved by the use of function overloaded and operator overloading also referred to as static binding or initial binding.

Compile Time Polymorphism Types

There are two varieties of compile-time polymorphism in C++:

1. Overloading of Functions
These functions are referred to as being overloaded when they share the same name but have different argument lists.Functions may become overloaded when the number or type of arguments changes. Function overloading occurs in C++ when there are numerous functions that have the same identity but different arguments.The kind ofnumber of the arguments may vary

Advantages of Function Overloading

The benefit of that is that we won't constantly need to think of new names.We don't need to assign different names for the two functions because they are both used to add integers. Writing programs is simple, and there aren't many function names to keep in mind. That is the advantage we currently enjoy.

Example program 1

#include <iostream>
using namespace std;
void add(int x, int y)
{
int sum = x + y;
cout<< "The value of the result is " << sum <<endl;
}
void add(int x, int y, int z)
{
    int sum = x + y + z;
cout<< "The value of the result is " << sum <<endl;
}
void Add(double x, double y)
{
    double sum = x + y;
cout<< "The value of the result is " << sum <<endl;
}
int main()
{
    Add (10, 20);
    Add (10, 5, 20);
    Add (3.3, 10.7);
    return 0;
}

Output

The value of the result is 30
The value of the result is 35
The value of the result is 14

Example 2

#include<iostream>
using namespace std;
int Sum(int x, int y)
{
    return x + y;
}
float Sum(float x, float y)
{
    return x + y;
}
int Sum(int x, int y, int z)
{
    return x + y + z;
}
int main()
{
cout<<Sum(10, 10) <<endl;
cout<<Sum(17.5f, 3.4f) <<endl;
cout<<Sum(11, 20, 3) <<endl;
    return 0;
}


Output

20
20.9
34

2. Overloading of operator

The possibility to overload operators is likewise available in C++. We define a new meaning for a C++ operator in Operator Overloading. Additionally, it alters the operator's workflow. For instance, we can concatenate two strings using the string class's operator (+).

We are aware that the purpose of this operator, which has two operands, is to add them. Therefore, the single operator "+" adds and concatenates strings when it is used between operands that are integers.

Advantages of operator overloading

To conduct operations like addition (+), multiplication (*), subtraction (-), conversion ("()"), increment and decrement (++, -), new operator, delete operator, and so on, we have several operators. This means that C++ has operators that can be used to do a variety of tasks. And certain data types are intended for these operators.

Example 1

#include<iostream>
using namespace std;
class Complex
{
    private:
        int real;
        int img;
    public:
        Complex (int r = 0, int i = 0)
        {
            real = r;
img = i;
        }
        Complex operator + (Complex x)
        {
            Complex temp;
temp.real = real + x.real;
temp.img = img + x.img;
            return temp;
        }
        void Display() 
{
cout<< real << "+i" <<img<<endl;
        }
};
int main()
{
    Complex C1 (3, 7);
    C1.Display();
    Complex C2 (5, 2);
    C2.Display();
    Complex C3;
    C3 = C1+C2;
    C3.Display();
}

Output

3+i7
5+i2
8+i9

Example 2

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


    public:
Count(int num = 0)
        {
            value = num;
        }


        void operator ++ (){
            ++value;
        }
        void Display()
        {
cout<< "Count: " << value <<endl;
        }
};
int main() {
    Count count1(10);
    count1.Display();
    ++count1;
    count1.Display();
    return 0;
}

Output

Count: 10
Count: 11

Related Topics

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.