0
0
C++programming~5 mins

Function overloading in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function overloading
O(n)
Understanding Time Complexity

Function overloading lets us use the same function name with different inputs.

We want to see how this affects the time it takes to run the program.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

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

int main() {
    int x = add(1, 2);
    int y = add(1, 2, 3);
    return 0;
}
    

This code defines two functions named add with different numbers of inputs and calls both.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Simple addition operations inside each function.
  • How many times: Each function runs once per call; no loops or recursion.
How Execution Grows With Input

Execution time grows only by how many times we call these functions.

Input Size (n)Approx. Operations
1 call1 or 2 additions
10 calls10 to 20 additions
100 calls100 to 200 additions

Pattern observation: The time grows linearly with the number of calls, not with input size inside the function.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly with how many times the overloaded functions are called.

Common Mistake

[X] Wrong: "Function overloading makes the program slower because it runs all versions of the function every time."

[OK] Correct: Only the matching function version runs based on the inputs; others are ignored, so no extra time is spent.

Interview Connect

Understanding how function overloading affects time helps you explain code efficiency clearly and confidently.

Self-Check

"What if one overloaded function called another overloaded function inside it? How would the time complexity change?"