Cover Image for What is function overloading in C++
96 views

What is function overloading in C++

Function overloading in C++ allows you to define multiple functions with the same name but different parameter lists within the same scope. The compiler distinguishes between these overloaded functions based on the number, type, and order of their parameters. This allows you to create functions that perform similar tasks but with different input data or behaviors.

Key characteristics of function overloading in C++:

  1. Same Function Name: Overloaded functions have the same name.
  2. Different Parameter Lists: Overloaded functions have different parameter lists, which may include differences in the number or type of parameters.
  3. Return Type: The return type of the overloaded functions can be the same or different. The return type alone is not sufficient to distinguish overloaded functions.

Here’s an example of function overloading:

C++
#include <iostream>

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

// Function to add two double numbers
double add(double a, double b) {
    return a + b;
}

// Function to concatenate two strings
std::string add(const std::string& str1, const std::string& str2) {
    return str1 + str2;
}

int main() {
    int sumInt = add(5, 3);
    double sumDouble = add(2.5, 3.7);
    std::string concatenatedString = add("Hello, ", "world!");

    std::cout << "Sum of integers: " << sumInt << std::endl;
    std::cout << "Sum of doubles: " << sumDouble << std::endl;
    std::cout << "Concatenated string: " << concatenatedString << std::endl;

    return 0;
}

In this example, the add function is overloaded three times:

  1. int add(int a, int b) takes two integer parameters and returns an integer.
  2. double add(double a, double b) takes two double parameters and returns a double.
  3. std::string add(const std::string& str1, const std::string& str2) takes two string parameters and returns a string.

The compiler determines which overloaded function to call based on the argument types passed when the function is invoked. In the main function, we demonstrate calling each overloaded version of the add function with different argument types.

Function overloading is a useful feature that promotes code reusability and improves code readability by allowing you to define multiple related functions with the same name. It’s commonly used for mathematical operations, string manipulation, and providing flexibility in function parameter types while keeping the interface consistent.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS