Skip to main content
Engineering LibreTexts

14.2: Overload a Function

  • Page ID
    29119
  • Function Overloading in C++

    Function overloading is a feature in C++ where two or more functions can have the same name but different parameters.

    When a function name is overloaded with different jobs it is called Function Overloading.

    In Function Overloading “Function” name should be the same and the arguments should be different.

    Function overloading can be considered as an example of polymorphism feature in C++.

    Following is a simple C++ example to demonstrate function overloading.

    #include <iostream>
    using namespace std;
     
    // a char, an unsigned char, and short also use this function
    void print(int inInt) {
      cout << " Here is int " << inInt << endl;
    }
    
    // a float argument is promoted to double and uses this function
    void print(double  inFloat) {
      cout << " Here is float " << inFloat << endl;
    }
    
    // this function is a character pointer - and is used for string arguments
    void print(char const *inChar) {
      cout << " Here is char* " << inChar << endl;
    }
     
    int main() {
      print(10);
      print(10.10);
      print("ten");
      return 0;
    }
    

    Output:

    Here is int 10 
    Here is float 10.1 
    Here is char* ten

    How  Function Overloading works?

    • Exact match:- (Function name and Parameter)
    • If an exact argument type match is NOT found:
      • then a char, an unsigned char, and short are promoted to an int - and use the first print function.
      • a float argument is promoted to double - and uses the second print function
    • If no match found:
      • C++ tries to find a match through the standard conversion.
    • ELSE ERROR

    Adapted from:
    "Function Overloading in C++" by devilchandraGeeks for Geeks is licensed under CC BY-SA 4.0