0
0
CppConceptBeginner · 3 min read

Compile Time Polymorphism in C++: Definition and Example

In C++, compile time polymorphism means the ability of the program to decide which function or method to call during compilation, not at runtime. It is achieved using techniques like function overloading and templates, allowing multiple functions with the same name but different parameters.
⚙️

How It Works

Compile time polymorphism works by letting the compiler choose the correct function to run based on the arguments you provide. Imagine you have a toolbox with several tools that look similar but do different jobs depending on the size or shape of the object you want to fix. The compiler picks the right tool before the program even runs.

This is different from runtime polymorphism, where the decision happens while the program is running. Compile time polymorphism is faster because the choice is made early, so the program doesn't waste time deciding later.

💻

Example

This example shows function overloading, a common way to do compile time polymorphism. The print function is defined twice: once for integers and once for strings. The compiler picks the right one based on what you send it.

cpp
#include <iostream>
#include <string>

void print(int number) {
    std::cout << "Integer: " << number << std::endl;
}

void print(const std::string& text) {
    std::cout << "String: " << text << std::endl;
}

int main() {
    print(42);           // Calls print(int)
    print("Hello");    // Calls print(string)
    return 0;
}
Output
Integer: 42 String: Hello
🎯

When to Use

Use compile time polymorphism when you want your program to be fast and efficient because the decisions are made before running. It is great for simple cases where you know all the possible function types ahead of time, like math operations or printing different data types.

For example, if you write a program that handles different shapes and you want to calculate their area, you can use function overloading to write one function for each shape type. This way, the compiler picks the right calculation automatically.

Key Points

  • Compile time polymorphism is decided by the compiler before the program runs.
  • It uses function overloading and templates to work.
  • It is faster than runtime polymorphism because no decision is needed during execution.
  • It is useful when all function variations are known in advance.

Key Takeaways

Compile time polymorphism lets the compiler pick the right function before running the program.
Function overloading and templates are common ways to achieve compile time polymorphism in C++.
It improves performance by avoiding decisions during program execution.
Use it when you know all function variations ahead of time for cleaner and faster code.