• Home
  • 6.12 Function Overloading

6.12 Function Overloading

View Categories

6.12 Function Overloading

1 min read

Table of Contents

Function overloading allows multiple functions to have the same name while having different parameter lists. The compiler determines which overloaded function to call based on the number, types, and order of the arguments supplied.

Function overloading allows related operations to use a common function name while supporting different types or combinations of input.

Source Code #

#include <iostream>

int add(int first, int second)
{
    return first + second;
}

double add(double first, double second)
{
    return first + second;
}

int main()
{
    int integer_result = add(10, 20);
    double decimal_result = add(10.5, 20.5);

    std::cout << "Integer Result: " << integer_result << '\n';
    std::cout << "Decimal Result: " << decimal_result << '\n';

    return 0;
}

Output #

Integer Result: 30
Decimal Result: 31

Explanation #

  • Two functions named add are defined with different parameter types.
  • int add(int first, int second) accepts two int parameters.
  • double add(double first, double second) accepts two double parameters.
  • These functions form an overloaded function set.
  • add(10, 20) selects the int version because both arguments are integers.
  • add(10.5, 20.5) selects the double version because both arguments are double values.
  • The compiler determines the appropriate overload during compilation based on the function arguments.
  • A function cannot be overloaded solely by changing its return type.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *