×

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

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 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.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 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.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 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.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.