Language: EN

cpp-sobrecarga-funciones

What is Function Overloading in C++

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

The C++ compiler decides which version of the function to invoke 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.

Syntax of Overloading

To use function overloading, functions must differ by at least one aspect of their parameters: either 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;
}

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

  • To sum two integers.
  • To sum three integers.
  • To sum 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);
}

Practical Examples

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