Compile-time polymorphism

Compile-time polymorphism, also known as static polymorphism, is resolved during the compilation of the program. It allows multiple methods to have the same name with different parameters.

Key Concepts

  1. Function Overloading:
    • Defining multiple functions with the same name but different parameter lists.
    • The compiler determines the appropriate function to call based on the arguments provided.
  2. Operator Overloading:
    • Allows operators to be redefined and used in user-defined types (classes).
    • Enhances readability and maintainability by enabling intuitive operations on objects.

Example

#include <iostream>
using namespace std;

// Function Overloading
class Math {
public:
    int add(int a, int b) {
        return a + b;
    }
    double add(double a, double b) {
        return a + b;
    }
};

int main() {
    Math math;
    cout << math.add(2, 3) << endl;        // Calls add(int, int)
    cout << math.add(2.5, 3.5) << endl;    // Calls add(double, double)
    return 0;
}