Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Compile Time Polymorphism in C++

Last Updated on December 26, 2023 by Ankit Kochar

Compile-time polymorphism is a fundamental concept in C++ programming that facilitates flexibility and efficiency in code execution. It allows developers to create versatile programs by enabling functions and classes to exhibit different behaviors based on the context they are used in, all resolved during compilation rather than runtime. In C++, compile-time polymorphism is primarily achieved through function overloading, templates, and inheritance, providing a powerful mechanism for creating reusable and adaptable code structures.

This article delves into the core principles of compile-time polymorphism in C++, exploring its various implementations, advantages, and best practices. From understanding the fundamental concepts to implementing them in practical scenarios, this guide aims to equip developers with the knowledge needed to leverage compile-time polymorphism effectively in their C++ projects.

What is Polymorphism in C++?

An important aspect of object-oriented programming is polymorphism, which makes it possible to treat objects of different classes as though they were objects of the same class by using virtual functions and inheritance. In other words, multiple forms are referred to as polymorphism.

A real-life example of polymorphism is the concept of a "vehicle". A vehicle can be a car, a truck, a motorcycle, or any other mode of transportation. Each type of vehicle has its own unique characteristics and behavior, but they all share certain common traits, such as the ability to move from one place to another.

There are mainly two types of polymorphism:

  • Compile Time Polymorphism in C++: Compile time polymorphism in C++ is invoked during the compile time of the program. There are two ways to achieve compile-time polymorphism in C++:

    • Function Overloading
    • Operator Overloading
  • Run Time Polymorphism in C++: Run time polymorphism in C++ is invoked during the run time of the program. There is one way to achieve the run time polymorphism in C++:

    • Function Overriding

What is Compile Time Polymorphism in C++?

The compile time polymorphism in C++ is a type of polymorphism, which refers to the ability of a programming language to determine the appropriate method or function to call at compile time-based on the types of arguments being passed.

There are a couple of ways to achieve compile time polymorphism in C++.

1. Function Overloading:

The C++ language’s function overloading feature enables us to define multiple functions that have the same name but different parameters. When we want to perform the same operation on various data types, or when we want to offer different levels of functionality depending on the quantity or kind of arguments passed, this can be helpful.

In C++, we simply define two or more functions with the same name but different parameters to overload a function. The compiler chooses which version of the function to call based on the number, type, and ordering of the arguments passed.

Let’s take an example to understand the compile time polymorphism in C++ using the function overloading.

// compile time polymorphism in C++
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
class PrepBytes {
public:

    // Function with 1 int parameter
    void add(int x,int y)
    {
        std::cout << "The Sum of "<< x <<" and "<<y <<" is: " << x+y<<"\n";
    }

    // Function with same name but
    // 1 double parameter
    void add(int x, int y, int z)
    {
        std::cout << "The Sum of "<< x <<", "<< y <<" and "<<z <<" is: " << x+y+z << "\n";
    }

    // Function with same name and
    // 2 int parameters
    void add(double x, double y)
    {
        std::cout << "The Sum of "<< x <<" and "<<y <<" is: " << x+y<< "\n";
    }
    
    void add(double x, double y, double z)
    {
        std::cout << "The Sum of "<< x << ", " << y <<" and "<< z <<" is: " << x+y+z<< "\n";
    }
    
};

int main()
{
    PrepBytes obj;

    obj.add(7,8);
    obj.add(10,14,16);
    obj.add(4.5, 6.2);
    obj.add(1.3, 4.6, 7.2);
    
    return 0;
}

Output:

The Sum of 7 and 8 is: 15
The Sum of 10, 14 and 16 is: 40
The Sum of 4.5 and 6.2 is: 10.7
The Sum of 1.3, 4.6 and 7.2 is: 13.1

In the above C++ program, the class Prepbytes contains several methods with the same name add. During compile time, it will be decided which method to call based on the given arguments in the function parameter. For example, if we give 3 int data type arguments in the add function then it will call the second add function.

2. Operator Overloading:

In C++, a feature called operator overloading enables operators like +, -, *, /, and others to be redefined for user-defined data types. As a result, we can specify what the operator does when used with objects belonging to our own class, which enables us to write more logical and expressive code.

In C++, we define a function that starts with the operator keyword and the symbol we want to overload. For instance, we might define a function with the following signature to overload the addition operator + for the class "MyClass":

MyClass operator+(const MyClass& obj) const;

The ampersand (&) indicates that the function takes its argument by reference rather than by value and the keyword "const" indicates that it does not modify the object it is called on.

Let’s take an example to understand the compile time polymorphism in C++ using operator overloading.

// compile time ploymorphism in C++
#include <iostream>
using namespace std;

class Complex {
public:
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
    Complex operator+(const Complex& obj) const {
        return Complex(real + obj.real, imag + obj.imag);
    }
    void display() const {
        cout << real << " + " << imag << "i" << endl;
    }
private:
    double real, imag;
};

int main() {
    Complex c1(1.0, 2.0), c2(2.0, 3.0);
    Complex c3 = c1 + c2; // calls the overloaded + operator
    c3.display(); 
    return 0;
}

Output:

3 + 5i

In this example, we define a class called "Complex" that represents complex numbers with a real and imaginary components. We overload the addition operator (+) by defining a method called "operator+" that takes a Complex object as a reference and returns a new Complex object representing the sum of the two Complex objects.

Conclusion
In conclusion, compile-time polymorphism stands as a cornerstone of C++ programming, offering a robust way to enhance code reusability, flexibility, and performance. By utilizing techniques like function overloading, templates, and inheritance, developers can create versatile and efficient programs that adapt to different data types and contexts without sacrificing performance.

Understanding the nuances of compile-time polymorphism not only enhances code readability and maintainability but also enables the development of scalable and adaptable software solutions. Mastery of these concepts empowers C++ programmers to write more concise, flexible, and efficient code, contributing to the creation of robust applications across various domains.

FAQs of compile time polymorphism in C++

Here are some FAQs related to Compile Time Polymorphism in C++.

1. What is the difference between compile-time polymorphism and runtime polymorphism in C++?
Compile-time polymorphism, achieved through techniques like function overloading, templates, and static polymorphism (using inheritance), resolves method calls at compile time. Runtime polymorphism, commonly achieved through dynamic polymorphism using virtual functions and inheritance, resolves method calls at runtime based on the actual object type.

2. How does function overloading contribute to compile-time polymorphism?
Function overloading allows the creation of multiple functions with the same name but different parameters within the same scope. During compilation, the appropriate function to execute is determined based on the number and types of arguments passed to it, contributing to compile-time polymorphism.

3. What are templates, and how are they related to compile-time polymorphism?
Templates in C++ enable the creation of generic functions and classes that can work with any data type. They allow for compile-time instantiation of code based on different data types, facilitating compile-time polymorphism by generating specific code for each data type at compile time.

4. What are the advantages of using compile-time polymorphism in C++?
Compile-time polymorphism offers several benefits, including improved code reusability, performance optimization through early binding, better error detection during compilation, and enhanced readability by providing a clear structure for different behaviors based on context.

5. When should I use compile-time polymorphism in my C++ programs?
Use compile-time polymorphism when you want to create flexible and efficient code that can handle multiple data types or contexts without sacrificing performance. It is beneficial when the behavior of functions or classes needs to be determined at compile time rather than runtime.

6. What are the advantages of compile-time polymorphism?
Compile-time polymorphism can help you write cleaner, more efficient code by allowing you to reuse function names and reduce redundancy. It also helps catch errors at compile time instead of at runtime, which can save you time and effort in debugging.

Leave a Reply

Your email address will not be published. Required fields are marked *