C++ Function Overloading

C++ Function Overloading: Same Name, Different Parameters

In C++, function overloading allows you to have multiple functions with the exact same name, as long as they have different parameters (different type or number of parameters).

This is a very powerful feature because it allows you to use a single, descriptive name for operations that are conceptually similar but work on different types of data.


1. Why Overload Functions?

Imagine you want to write a function that adds two numbers. You might want to add two integers, or you might want to add two doubles (decimals).

Without overloading, you would have to invent different names for each function:

Without Overloading Example

int addInts(int x, int y) {
  return x + y;
}

double addDoubles(double x, double y) { return x + y; }

This makes your code harder to read and remember. With function overloading, you can simply call them both add!


2. Example of Function Overloading

Let's overload the add function so it can handle both integers and doubles smoothly.

Function Overloading Example

#include <iostream>
using namespace std;

// Function 1: Adds two integers int add(int x, int y) { return x + y; }

// Function 2: Adds two doubles double add(double x, double y) { return x + y; }

int main() { int intResult = add(10, 5); // Calls the int version double doubleResult = add(4.3, 2.1); // Calls the double version

cout << "Int result: " << intResult << "\n"; cout << "Double result: " << doubleResult << "\n";

return 0; }

The C++ compiler is smart enough to know which function to call based on the arguments you pass in. If you pass integers, it calls the integer version. If you pass doubles, it calls the double version!


3. Overloading with Different Number of Parameters

You can also overload functions by changing the number of parameters.

Different Number of Parameters

#include <iostream>
using namespace std;

// Calculates area of a square int calculateArea(int side) { return side * side; }

// Calculates area of a rectangle int calculateArea(int length, int width) { return length * width; }

int main() { cout << "Square Area: " << calculateArea(5) << "\n"; cout << "Rectangle Area: " << calculateArea(5, 10) << "\n"; return 0; }


Exercise

?

Which of the following is required for function overloading in C++?