🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Function Overloading

C++ Function Overloading Example

C++ Function Overloading Example

Function overloading is a feature in C++ that allows a class to have multiple functions with the same name but different parameter lists. The compiler distinguishes between these functions based on the number or types of parameters. Function overloading is a form of polymorphism that provides flexibility and readability in the code.

Example: Overloaded Functions


#include <iostream>

// Function overloading
int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

std::string add(const std::string& str1, const std::string& str2) {
    return str1 + str2;
}

int main() {
    // Function calls with different parameter lists
    int sumInt = add(3, 4);
    double sumDouble = add(3.5, 4.2);
    std::string concatenatedStr = add("Hello, ", "World!");

    // Display the results
    std::cout << "Sum (int): " << sumInt << std::endl;
    std::cout << "Sum (double): " << sumDouble << std::endl;
    std::cout << "Concatenation: " << concatenatedStr << std::endl;

    return 0;
}

In this example, the add function is overloaded three times. It has different parameter lists for integers, doubles, and strings. When the function is called, the compiler determines which version of the function to execute based on the argument types.

Key Points about Function Overloading:

  1. Same Function Name: All overloaded functions must have the same name.
  2. Different Parameter Lists: Overloaded functions must differ in terms of the number or types of parameters. The return type alone is not sufficient to distinguish between functions.
  3. Return Type Doesn't Matter: The return type of the functions can be the same or different.
  4. Default Arguments and Overloading: Functions with default arguments contribute to overloading.

Function overloading is commonly used in situations where the same operation makes sense for different types or numbers of parameters. It promotes code reuse and enhances the readability of the code. Keep in mind that overloading should be used judiciously to avoid confusion and maintain clarity in your code.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.