The Wayback Machine - https://web.archive.org/web/20240723231957/https://www.geeksforgeeks.org/compile-time-vs-run-time-polymorphism-difference-in-cpp/
Open In App

Difference Between Compile Time And Run Time Polymorphism In C++

Last Updated : 20 Oct, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++.

What is Polymorphism?

Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms.

For example,

Your DAD is your father. He’s your mom’s Husband. He’s your grandma’s son as well. Thus here your DAD is exhibiting many forms. He’s a father, son, husband, brother, etc.

In C++, polymorphism can be divided into two types:

  1. Compile-time Polymorphism
  2. Run-time Polymorphism

Compile Time Polymorphism in C++

In compile-time polymorphism, the compiler determines which function or operation to call based on the number, types, and order of arguments. It is also called Static Polymorphism as the function calls are statically binded to its definition.

It is further categorized into two types:

  1. Function Overloading
  2. Operator Overloading

1. Function Overloading

When multiple functions in a class with the same name but different parameters exist, these functions are said to be overloaded.

  • The functions can be overloaded by using a different number of arguments and by using different types of arguments.
  • If two same name and same argument functions just vary in their return type then such function isn’t overloaded.

Example

C++




// C++ Code to illustrate Function Overloading
#include <iostream>
using namespace std;
  
// Function to be overloaded
int add(int x, int y, int z = 0, int w = 0)
{
    return (x + y + z + w);
}
  
int main()
{
    // Passing different number of arguements
    cout << add(10, 20) << endl;
    cout << add(10, 20, 30) << endl;
    cout << add(10, 20, 30, 40) << endl;
  
    return 0;
}


Output

30
60
100

Operator Overloading

We know that, “+” is used for addition or concatenation. Now, if I want to perform my customized operation i.e. upon calling +, I want to print “Hello Geek” or I want to perform subtraction instead of addition. In such cases, we use operator overloading.

Operator overloading is the process of defining different operations for the operator that vary depending on the argument type.

  • Precedence and associativity remain intact in operators.
  • List of operators that cannot be overloaded in C++ are ::, .*, ., ?:
  • Operators = and & are already overloaded in C++, so we should avoid overloading them.

Example

C++




// C++ Code to illustrate Operator Overloading
#include <iostream>
using namespace std;
  
class B {
public:
    int a, b;
  
public:
    int add() { return a + b; }
  
    // overloading + operator for B class
    void operator+(B& obj)
    {
        int val1 = this->a;
        int val2 = obj.a;
        cout << "Output " << val2 - val1 << endl;
    }
};
  
// driver code
int main()
{
    B obj1, obj2;
    obj1.a = 4;
    obj2.a = 17;
    obj1 + obj2;
    return 0;
}


Output

Output 13

Run Time Polymorphism

In run-time polymorphism, the decision of which function to call is determined at runtime based on the actual object type rather than the reference or pointer type. It is also known as Dynamic Polymorphism because the function calls are dynamically bonded at the runtime.

Run Time Polymorphism can be exhibited by:

  • Method Overriding using Virtual Functions

Method Overriding

Method overriding refers to the process of creating a new definition of a function in a derived class that is already defined inside its base class. Some rules that must be followed while overriding a method are:

  • Method names must be the same.
  • Method parameters must be the same.

Virtual Function

  • Virtual Function is a member function that is declared as virtual in the base class and it can be overridden in the derived classes that inherit the base class.
  • Virtual functions are generally declared in the base class and are typically defined in both the base and derived classes.

Example

C++




// C++ Code to illustrate Virtual Function
#include <iostream>
using namespace std;
  
// base class
class Base {
public:
    // virtual function
    virtual void print() { cout << "base"; }
};
  
// derived class
class Derived : public Base {
public:
    // method overriding
    void print() override { cout << "derived"; }
};
  
// driver code
int main()
{
    Base* obj = new Derived();
    obj->print();
    delete obj;
    return 0;
}


Output

derived

Difference Between Compile Time And Run Time Polymorphism

Compile-Time Polymorphism

Run-Time Polymorphism

It is also called Static Polymorphism. It is also known as Dynamic Polymorphism.
In compile-time polymorphism, the compiler determines which function or operation to call based on the number, types, and order of arguments. In run-time polymorphism, the decision of which function to call is determined at runtime based on the actual object type rather than the reference or pointer type.
Function calls are statically binded. Function calls are dynamically binded.

Compile-time Polymorphism can be exhibited by:

1. Function Overloading
2. Operator Overloading

Run-time Polymorphism can be exhibited by Function Overriding.

Faster execution rate. Comparatively slower execution rate.
Inheritance in not involved. Involves inheritance.


Similar Reads

VS Code | Compile and Run in C++
In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in
3 min read
How To Compile And Run a C/C++ Code In Linux
C Programming Language is mainly developed as a system programming language to write kernels or write an operating system. C++ Programming Language is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance. In this article, we will be compiling and executing the C Programming Language codes and also C
3 min read
What is the difference between the $parse, $interpolate and $compile services?
In AngularJS applications, the $parse, $interpolate and $compile services are the most important components as these services are used for data binding. Here, the $parse is mainly responsible for parsing and evaluating the expressions in the context of the application's scope. The $interpolate handles the interpolation of expressions and the $compi
6 min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheritancesHybrid inheritanceHierarchical inheritanceEx
5 min read
How to compile 32-bit program on 64-bit gcc in C and C++
Mostly compiler(gcc or clang) of C and C++, nowadays come with default 64-bit version. Well it would be a good option in terms of speed purposes. But it would lead to problem, if someone wants to run their program as a 32-bit rather than 64-bit for testing or debugging purposes. Therefore we must have a knowledge about this.Before proceeding forwar
2 min read
Write a C program that won't compile in C++
Although C++ is designed to have backward compatibility with C, there can be many C programs that would produce compiler errors when compiled with a C++ compiler. Following is the list of the C programs that won’t compile in C++: Calling a function before the declarationUsing normal pointer with const variableUsing typecasted pointersDeclaring cons
4 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
SAP ABAP | Polymorphism
Polymorphism in SAP ABAP is a core principle in Object-Oriented Programming (OOP) that enables different classes to be handled as instances of a shared class via a common interface. This allows developers to apply techniques in various ways while storing a constant user interface. In SAP ABAP, the integration of polymorphism is pivotal for augmenti
6 min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
RTTI (Run-Time Type Information) in C++
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution. Runtime Casts The runtime cast, which checks that the cast is valid, is the
3 min read
Practice Tags :
three90RightbarBannerImg