All Courses
OOP: POLYMORPHISM

Function Overloading: Compile-time Polymorphism

Function overloading means multiple functions have the same name but different parameter lists.

The compiler chooses the correct function by checking:

  • Number of arguments.
  • Types of arguments.
  • Order of argument types.

Return type alone is not enough to overload a function.

Complete Example

#include <iostream>
using namespace std;

class Calculator {
public:
    int add(int a, int b) const {
        return a + b;
    }

    double add(double a, double b) const {
        return a + b;
    }

    int add(int a, int b, int c) const {
        return a + b + c;
    }
};

int main() {
    Calculator calculator;

    cout << calculator.add(2, 3) << endl;
    cout << calculator.add(2.5, 3.5) << endl;
    cout << calculator.add(1, 2, 3) << endl;

    return 0;
}

Output:

5
6
6

What Cannot Overload

This is not valid overloading:

int getValue();
double getValue();

The parameter list is the same, so the compiler cannot choose based only on return type.

Overloading vs Overriding

Topic Function overloading Function overriding
Class relationship not required requires inheritance
Function name same same
Parameter list different same or compatible
Decision time compile time runtime if virtual
Keyword virtual not needed needed for runtime polymorphism

Viva Answer

Function overloading is compile-time polymorphism where multiple functions have the same name but different parameter lists. The compiler selects the correct function during compilation based on the arguments.

Quick Check

  1. Can return type alone overload a function?
  2. Why is function overloading compile-time polymorphism?
  3. What is the key difference between overloading and overriding?