How to Overload a Function in C++

Function overloading in C++ allows more than one function to have the same name. The issue of which function to call is resolved when compiling the program using the input parameter list which must be unique. The following steps will show how to overload a function in C++.

Instructions

    • 1

      Look at the following example of an overloaded function:

      int test(char x, char y);
      int test(char x, char y, char z);
      int test(int x, int y);
      int test(int x, int y, int z);

    • 2

      Observe that all 4 functions in Step 1 have the same name of "test" but have unique parameter lists. The first function takes 2 char values as input. The second takes 3 char values. The third takes 2 ints and the fourth takes 3 ints.

    • 3

      Implement each function. The following code is an example of how the first function of "test" might be implemented:

      int test(char x, char y)
      {
      return (int)(x + y);
      }

    • 4

      Notice that the input parameters of the first function declared in Step 1 matches the parameters in the function implementation shown in Step 3 (2 char values). Notice further that the return value is explicitly type cast so that it matches the int specified in the function's declaration.

Tips & Warnings

  • Type cast the data properly so that the compiler is able to determine which overloaded functions will be called. Otherwise, the compiler will generate an ambiguity error.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured