cpp-sobrecarga-funciones

What is Function Overloading in C++

  • 4 min

Function overloading is a feature of C++ that allows defining multiple versions of functions with the same name but with different parameter lists.

The C++ compiler decides which version of the function to call based on the types and number of arguments passed in the function call.

This provides flexibility and avoids the need to use different function names for similar operations.

If you want to learn more, check out the Introduction to Programming Course

Overloading Syntax

To use function overloading, functions must differ in at least one aspect of their parameters: the type or the number of arguments.

#include <iostream>

// Function to sum two integers
int Sumar(int a, int b) {
    return a + b;
}

// Function to sum three integers
int Sumar(int a, int b, int c) {
    return a + b + c;
}

// Function to sum two floating-point numbers
double Sumar(double a, double b) {
    return a + b;
}

int main() {
    std::cout << "Sum of 2 and 3: " << Sumar(2, 3) << std::endl;           // Calls Sumar(int, int)
    std::cout << "Sum of 1, 2 and 3: " << Sumar(1, 2, 3) << std::endl;    // Calls Sumar(int, int, int)
    std::cout << "Sum of 2.5 and 3.5: " << Sumar(2.5, 3.5) << std::endl;   // Calls Sumar(double, double)

    return 0;
}
Copied!

In this example, the Sumar function is overloaded in three ways:

  • To add two integers.
  • To add three integers.
  • To add two floating point numbers.

It is not possible to use overloading based solely on the return type. For example, the following case would not be valid:

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

// This is not valid, as it only differs by the return type
double MiMetodo(int a, int b) {
    return static_cast<double>(a + b);
}
Copied!

Practical Examples

These examples are intended to show how to use overloading. It does not mean it is the best way to solve the problem they address. Usually, there are better alternatives.