Menu
Coddy logo textTech

Function Overloading

Part of the Fundamentals section of Coddy's C++ journey — lesson 54 of 74.

Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. When you call an overloaded function, the C++ compiler determines the most appropriate definition to use by comparing the argument types you've used in the call with the parameter types specified in the definitions. If no matching function is found, the compiler will generate an error.

Here's an example of function overloading:

int add(int a, int b) {
	return a + b;
}
double add(double a, double b) {
	return a + b;
}
int main() {
	int sum1 = add(5, 3); // Calls the first version of add
	double sum2 = add(2.5, 3.7); // Calls the second version of add
    return 0;
}

In this example, we have two functions named add. One takes two int parameters, and the other takes two double parameters. Depending on the types of the arguments we pass to add, the appropriate version of the function is called.

It's important to note that the return type alone is not sufficient to overload a function. The functions must differ in their parameter lists.

Cheat sheet

Function overloading allows multiple functions with the same name but different parameters. The compiler selects the appropriate function based on argument types:

int add(int a, int b) {
	return a + b;
}
double add(double a, double b) {
	return a + b;
}
int main() {
	int sum1 = add(5, 3); // Calls int version
	double sum2 = add(2.5, 3.7); // Calls double version
    return 0;
}

Functions must differ in their parameter lists - return type alone is not sufficient for overloading.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals